【问题标题】:Animate Circle Javascript Canvas动画圆圈 Javascript 画布
【发布时间】:2021-12-31 03:49:08
【问题描述】:

我正在尝试为从一个位置到另一个位置的移动圆圈设置动画。在下面的示例中,它是从 (10, 10) 到 (50, 50) 下面是我的 Bullet 类的代码。当用户单击空间时,我会创建一个新的 Bullet 对象并尝试对其进行动画处理。如何制作流畅的动画?

class Bullet{
    
    constructor(x, y){
        this.x = x;
        this.y = y;
        this.size = 10;
    }

    draw(){
        ctx.fillStyle = "green";
        ctx.beginPath();
        ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI)
        ctx.fill();
    }
    fire(locationX, locationY){
        
    }
}

document.addEventListener('keydown', function(e){
        if(e.key == ' '){
            var currBullet = new Bullet(10, 10);
            currBullet.fire(50, 50);
        }
});

function reset(){
    ctx.clearRect(0, 0, w, h);
}

【问题讨论】:

    标签: javascript animation html5-canvas


    【解决方案1】:

    您可以使用requestAnimationFrame 为子弹设置动画。这样做的总体目标是什么?你打算从 (10, 10) 到 (50, 50) 发射子弹吗?是否需要限制行驶距离?还是会根据玩家面对的方向朝一个方向射击?你想限制子弹的数量吗?

    此代码可以满足您的要求,但非常有限。

    const canvas = document.getElementById("canvas");
    const ctx = canvas.getContext("2d");
    canvas.width = 200;
    canvas.height = 200;
    
    let bullets = [];
    
    class Bullet{
        constructor(x, y){
            this.x = x;
            this.y = y;
            this.size = 10;
        }
    
        draw(){
            ctx.fillStyle = "green";
            ctx.beginPath();
            ctx.arc(this.x, this.y, this.size, 0, 2 * Math.PI)
            ctx.fill();
        }
        update(){
            this.x += 1
            this.y += 1
        }
    }
    
    document.addEventListener('keydown', function(e){
            if(e.code === 'Space'){
                fire()      
            }
    });
    
    function fire() {
        bullets.push(new Bullet(10, 10))
    }
    
    function animate() {
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      for (let i=0; i < bullets.length; i++) {
        bullets[i].draw()
        bullets[i].update()
        if (bullets[i].x >= 50 && bullets[i].y >= 50) {
          bullets.splice(i, 1)
        }
      }
      
      requestAnimationFrame(animate)
    }
    animate()
    &lt;canvas id='canvas'&gt;&lt;/canvas&gt;

    【讨论】:

    • 是的,我打算从一个坐标向另一个坐标发射子弹。我可能会限制距离并让方向朝向鼠标位置。我尝试运行您的代码 sn-p,但没有任何反应。
    • 你按空格键了吗?对我来说很好。
    • 哦,对不起,我忘了。感谢您的帮助,它有效。
    • 这里有一个更高级的例子。使用鼠标拍摄codepen.io/jfirestorm44/pen/oNWrmwy
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    • 1970-01-01
    • 2019-10-06
    • 2021-11-03
    • 1970-01-01
    相关资源
    最近更新 更多