开发一个简单的 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/