繁体   English   中英

JavaScript canvas:球留下了痕迹

[英]JavaScript canvas: Ball leaving a trail behind it

开发一个简单的画布应用程序,您可以用枪射击子弹,但是子弹留下了痕迹。 我尝试使用clearRect清除画布,并通过将画布的宽度设置为其自身,但是没有运气。 这是一个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;
    }
};

update():

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,包括“ trail”。

您需要在每个Bullet上创建一个新的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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM