JavaScript Canvas : Ball leaving a trail behind it

标签 javascript html canvas

开发一个简单的 Canvas 应用程序,您可以用枪射击子弹,但子弹会在后面留下痕迹。我尝试使用clearRect 并通过将 Canvas 的宽度设置为自身来清除 Canvas ,但没有成功。这是 jsFiddle 。相关片段:

Bullet.原型(prototype):

Bullet.prototype = {
    render: function () {
        ctx.fillStyle = this.color;
        ctx.arc(this.coordinates.x, this.coordinates.y, this.size.radius, 0, Math.PI * 2, false);
        ctx.fill();
        return this;
    },
    animate: function () {
        this.coordinates.x += this.velocity.speed.x;
        return this;
    }
};

更新():

function update() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    gun.render();
    gun.shoot();
    bullets.forEach(function(bullet) {
        bullet.render().animate();
    });
    requestAnimationFrame(update);
}

如何防止球留下痕迹?

最佳答案

在每个 Bullet.draw() 上,您都会向同一个 Path2d 添加更多 arc 形状。 然后,ctx.fill() 将应用于整个 Path2d,包括“轨迹”。

您需要在每个项目符号处创建一个新的 Path2d。

Bullet.prototype = {
    render: function () {
        ctx.fillStyle = this.color;
        ctx.beginPath(); // this is a new Path2d
        ctx.arc(this.coordinates.x, this.coordinates.y, this.size.radius, 0, Math.PI * 2, false);
        ctx.fill();
        return this;
    },
    animate: function () {
        this.coordinates.x += this.velocity.speed.x;
        return this;
    }
};

请注意,由于 arc(x,y,radius,0,2*Math.PI,0) 确实是一个闭合弧(圆),因此您不需要调用 ctx.closePath().

关于JavaScript Canvas : Ball leaving a trail behind it,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33536800/

相关文章:

php - 如何在网站中包含虚拟键盘(数字键盘)?

html - 水平CSS菜单问题

javascript - 用JS设置元素宽度超过html innerWidth

javascript - Angularjs - 乘以货币

javascript - 获取并检查 NodeJS 中读取的 JSON 值

javascript - 类名未添加到 Div

javascript - 卡在 Canvas /JS 动画中

javascript - 如何减少以下 HTML 5 canvas 游戏的延迟?

javascript - CSS - 定位滚动 div

javascript - dom 加载后,如何使 jquery 元素对生成的元素起作用?