簡體   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