【问题标题】:Why won't the image load为什么图片加载不出来
【发布时间】:2021-02-23 10:38:10
【问题描述】:

代码有什么问题,我找不到问题。我认为是因为 drawFrame 和 loadImage 功能,但我不知道。那么有没有办法让图像加载,你仍然可以移动它并拍摄?

当我尝试删除 drawFrame 函数时,没有任何效果。如果可行的话,有没有办法将子弹从正方形变成圆形?

<html>

<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta charset="UTF-8">
    <style>
        html,
        body {
            width: 100%;
            height: 100%;
            margin: 0;
        }

        canvas {
            cursor: crosshair;
            background-color: cornflowerblue;
        }
    </style>
</head>


<body>
    <canvas id="Trump"></canvas>



    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>


        (async function main() {
            var canvas = document.getElementById('Trump');
            if (!canvas.getContext) return;
            var ctx = canvas.getContext('2d');
            ctx.canvas.width = window.innerWidth;
            ctx.canvas.height = window.innerHeight;

            //const fps = 60;
            const ronaNum = 30; // number of particles at start
            const ronaSize = 70; // corona size
            const ronaSpeed = 100; // speed
            let chinabmg;


            function draw() {

                $("canvas").one("click", function () {
                    chinabmg = new sound("stankytrumpchina.mp3");
                    chinabmg.play();

                });
                //mutes when clicked on m
                document.body.onkeyup = function (e) {
                    if (e.keyCode == 77) { chinabmg.stop() }
                };


                //compatability            
                var requestAnimationFrame = window.requestAnimationFrame || //Chromium 
                    window.webkitRequestAnimationFrame || //Webkit
                    window.mozRequestAnimationFrame || //Mozilla Geko
                    window.oRequestAnimationFrame || //Opera Presto
                    window.msRequestAnimationFrame || //IE Trident?
                    function (callback) { //Fallback function
                        window.setTimeout(callback, 1000 / 60);
                    };

                var DrawX = 0;
                var DrawY = 0;
                var time = 0;
                var width = canvas.width;
                var height = canvas.height;
                var offTop = canvas.offsetTop;
                var offLeft = canvas.offsetLeft;
                var rectWidth = 15;
                var rectHeight = 15;
                var speed = 1;
                var x = width / 2;
                var y = height / 2;
                var size = 30;
                var id = 0;
                var bulletId = 0;



                function sound(src) {
                    this.sound = document.createElement("audio");
                    this.sound.src = src;
                    this.sound.setAttribute("preload", "auto");
                    this.sound.setAttribute("controls", "none");
                    this.sound.setAttribute("loop", "auto");
                    this.sound.style.display = "none";
                    document.body.appendChild(this.sound);
                    this.play = function () {
                        this.sound.play();
                    }
                    this.stop = function () {
                        this.sound.pause();
                    }
                }



                function player(id, color, size, x, y) {
                    this.id = id;
                    this.color = color;
                    this.size = size;
                    this.x = x;
                    this.y = y;
                    this.speed = speed;
                }
                var playerList = [];

                function addPlayer(color, size, x, y) {
                    playerList[id] = new player(id, color, size, x, y);
                    id += 1;
                }
                addPlayer("blue", size, width / 2 - 50, height / 2);


                var pressedKeys = [];




                function moveLeft(checkId, checkX, checkY, cSize, cSpeed, cKey) {
                    var x = checkX - cSpeed;
                    var y = checkY - cSpeed;
                    var x2 = checkX + cSize + cSpeed;
                    var y2 = checkY + cSize + cSpeed;
                    if (x > 0) {
                        playerList[checkId].x = checkX - cSpeed;
                    } else {
                        playerList[checkId].x = 0;
                    }
                }

                function moveUp(checkId, checkX, checkY, cSize, cSpeed, cKey) {
                    var x = checkX - cSpeed;
                    var y = checkY - cSpeed;
                    var x2 = checkX + cSize + cSpeed;
                    var y2 = checkY + cSize + cSpeed;
                    if (y > 0) {
                        playerList[checkId].y = checkY - cSpeed;
                    } else {
                        playerList[checkId].y = 0;
                    }
                }

                function moveRight(checkId, checkX, checkY, cSize, cSpeed, cKey) {
                    var x = checkX - cSpeed;
                    var y = checkY - cSpeed;
                    var x2 = checkX + cSize + cSpeed;
                    var y2 = checkY + cSize + cSpeed;
                    if (x2 < width) {
                        playerList[checkId].x = checkX + cSpeed;
                    } else {
                        playerList[checkId].x = width - cSize;
                    }
                }

                function moveDown(checkId, checkX, checkY, cSize, cSpeed, cKey) {
                    var x = checkX - cSpeed;
                    var y = checkY - cSpeed;
                    var x2 = checkX + cSize + cSpeed;
                    var y2 = checkY + cSize + cSpeed;
                    if (y2 < height) {
                        playerList[checkId].y = checkY + cSpeed;
                    } else {
                        playerList[checkId].y = height - cSize;
                    }
                }

                function Move(checkId, checkX, checkY, cSize, cSpeed, cKey) {



                    if (checkId === 0) {
                        switch (cKey) {
                            case 65:
                                // left
                                moveLeft(checkId, checkX, checkY, cSize, cSpeed, cKey);
                                break;

                            case 87:
                                // up 
                                moveUp(checkId, checkX, checkY, cSize, cSpeed, cKey);
                                break;

                            case 68:
                                // right         
                                moveRight(checkId, checkX, checkY, cSize, cSpeed, cKey);
                                break;

                            case 83:
                                // down         
                                moveDown(checkId, checkX, checkY, cSize, cSpeed, cKey);
                                break;

                            default:
                                return; // exit this handler for other keys 
                        }
                    }

                }

                var validKeys = [];
                validKeys[0] = "65,87,68,83-107,109,80";

                // == KEYDOWN ==
                $(document.body).keydown(function (e) {
                    e.preventDefault();

                    //go through all players
                    $.each(playerList, function (i, currentPlayer) {
                        if (validKeys[currentPlayer.id].indexOf(e.which) == -1) return true;
                        if (!pressedKeys[e.which]) {
                            //set interval for the function
                            pressedKeys[e.which] = setInterval(function () {
                                Move(currentPlayer.id, currentPlayer.x, currentPlayer.y, currentPlayer.size, currentPlayer.speed, e.which);
                            }, 5);
                        }
                    });
                });

                // == KEYUP ==    
                $(document.body).keyup(function (e) {
                    if (pressedKeys[e.which]) {
                        clearInterval(pressedKeys[e.which]);
                        delete pressedKeys[e.which];
                    }
                });

                //===============================    SHOOTING   ===============================

                //Bullets
                function bullet(id, color, size, speed, x, y, eX, eY) {
                    this.id = id;
                    this.color = color;
                    this.size = size;
                    this.x = x;
                    this.y = y;
                    this.eX = eX;
                    this.eY = eY;
                    this.velocityX = 1;
                    this.velocityY = 1;
                    this.speed = 9;
                }

                var bulletList = [];

                function addBullet(color, bsize, bspeed, x, y, eX, eY) {
                    bulletList[bulletId] = new bullet(bulletId, color, bsize, 9, x, y, eX, eY);
                    bulletId += 1;
                }

                function updateBullet(bullet, player) {
                    var dx = (bullet.eX - player.x);
                    var dy = (bullet.eY - player.y);
                    var mag = Math.sqrt(dx * dx + dy * dy);
                    bullet.velocityX = (dx / mag) * 9;
                    bullet.velocityY = (dy / mag) * 9;
                    bullet.x += bullet.velocityX;
                    bullet.y += bullet.velocityY;
                }

                // Add event listener for `click` events.
                canvas.onmousedown = function (e) {
                    addBullet("#696969", 10, 2, playerList[0].x, playerList[0].y, e.x, e.y);
                };

                //corona part
                let corona = [];
                createCoronaParticles();
                // game loop
                //setInterval(update, 1000 / fps);

                function createCoronaParticles() {
                    corona = [];
                    let cx, cy;
                    for (var i = 0; i < ronaNum; i++) {
                        do {
                            cx = Math.floor(Math.random() * canvas.width);
                            cy = Math.floor(Math.random() * canvas.height);
                        } while (noSpawnOnFigure(canvas.height / 2, canvas.width / 2, cy, cx) < ronaSize * 5);
                        corona.push(newParticle(cx, cy));
                    }
                }

                function noSpawnOnFigure(cy1, cx1, cy2, cx2) {
                    return Math.sqrt(Math.pow(cy2 - cy1, 2) + Math.pow(cx2 - cx1, 2));
                }

                function newParticle(cx, cy) {
                    let rona = {
                        ca: Math.random() * Math.PI * 2, //radians
                        cr: ronaSize / 2,
                        cx: cx,
                        cy: cy,
                        cxv: Math.random() * ronaSpeed / 60 * (Math.random() < 0.5 ? 1 : -1),
                        cyv: Math.random() * ronaSpeed / 60 * (Math.random() < 0.5 ? 1 : -1)
                    };
                    return rona;
                }
                // function update() {

                // }

                // ======= DRAWING =======      
                function drawFrame() {
                    requestAnimationFrame(drawFrame);
                    ctx.font = "15pt Georgia"; // sets the font and font size of the text
                    ctx.clearRect(0, 0, width, height);
                    $.each(playerList, function (index, currentPlayer) {
                        //debug 
                        


                        //draw players                           
                        function loadImage(path) {
                let image = new Image();
                let promise = new Promise((resolve, reject) => {
                    image.onload = () => resolve(image);
                    image.onerror = reject
                });
                image.src = path;
                return promise;
                
            }

            loadImage.src = 'trump.gif';

                    });
                    //draw bullets
                    $.each(bulletList, function (index, bullet) {
                        updateBullet(bullet, playerList[0]);
                        ctx.fillStyle = bullet.color;
                        ctx.fillRect(bullet.x, bullet.y, bullet.size, bullet.size);
                    });
                    // canvas
                    //ctx.clearRect(0, 0, canvas.width, canvas.height);
                    // draw corona particles
                    ctx.strokeStyle = "rgb(150, 0, 0)";
                    ctx.lineWidth = 20;
                    let ca, cr, cx, cy;
                    for (let i = 0; i < corona.length; i++) {

                        // get properties
                        ca = corona[i].ca;
                        cr = corona[i].cr;
                        cx = corona[i].cx;
                        cy = corona[i].cy;

                        // draw path
                        ctx.beginPath();
                        ctx.fillStyle = "rgb(200, 0, 0)"
                        ctx.moveTo(
                            cx + cr * Math.cos(ca),
                            cy + cr * Math.sin(ca)
                        );

                        // draw circle
                        for (let j = 1; j < 180; j++) {
                            ctx.lineTo(
                                cx + cr * Math.cos(ca + j * Math.PI * 2 / 180),
                                cy + cr * Math.sin(ca + j * Math.PI * 2 / 180)
                            );
                        }

                        ctx.closePath();
                        ctx.stroke();
                        ctx.fill();

                        // move particles
                        corona[i].cx += corona[i].cxv;
                        corona[i].cy += corona[i].cyv;

                        // particle edge of screen
                        if (corona[i].cx < 0 - corona[i].cr) {
                            corona[i].cx = canvas.width + corona[i].cr;
                        } else if (corona[i].cx > canvas.width + corona[i].cr) {
                            corona[i].cx = 0 - corona[i].cr
                        }
                        if (corona[i].cy < 0 - corona[i].cr) {
                            corona[i].cy = canvas.height + corona[i].cr;
                        } else if (corona[i].cy > canvas.height + corona[i].cr) {
                            corona[i].cy = 0 - corona[i].cr
                        }
                    }

                }
                drawFrame();
            }
            $(draw);
        }
        )();
    </script>



</body>

</html>

【问题讨论】:

  • 你有什么错误吗?
  • 错字: loadImage.src = 'trump.gif'; -> loadImage( 'trump.gif' );
  • @EriksKlotins no
  • @Kaiido 在我编辑时仍然无法工作

标签: javascript html image canvas


【解决方案1】:
                    //draw players                           
                    function loadImage(path) {
                        let image = new Image();
                        let promise = new Promise((resolve, reject) => {
                            image.onload = () => resolve(image);
                            image.onerror = reject
                        });
                        image.src = path;

                        //Add the following line
                        ctx.drawImage(image,playerList[0].x,playerList[0].y);

                        return promise;

                    }
                    // change loadImage.src = 'trump.gif' into this

                    loadImage('trump.gif');

【讨论】:

  • @ShopEySwing 现在加载正常,只需添加 ctx.drawImage(image,playerList[0].x,playerList[0].y);并将 loadImage.src = 'trump.gif' 替换为 loadImage('trump.gif');
  • 谢谢,你知道我如何重新缩放图像吗?
  • 有没有办法让它从中间射出,因为现在venter就像在精灵的上方和左侧?
猜你喜欢
  • 2021-09-26
  • 2016-04-22
  • 1970-01-01
  • 1970-01-01
  • 2020-02-25
  • 2020-07-14
相关资源
最近更新 更多