このループで作成された各円にそれぞれの色を割り当てたいとします。今では、すべての$ circleオブジェクトは異なる色を持っていますが、それらはすべて同じ色に設定されています。私は、パスを閉じるか、次のループの前に書き込む必要があることを読んでいます。これは私がしたことをかなり確信していますが、それでも動作しませんでした。私のコードは以下の通りです:キャンバスのfillStyleをループに変更する
drawCircles: function() {
this.ctx.beginPath();
for(var i = 0; i < this.circles.length; i++){
var $circle = this.circles[i];
this.ctx.fillStyle = $circle.color; //blue
var tx = $circle.destX - $circle.x,
ty = $circle.destY - $circle.y,
dist = Math.sqrt(tx*tx+ty*ty);
if(tx > 0){
$circle.x += (tx/dist) * ($circle.speed > 0 ? $circle.speed -= 0.005 : $circle.speed += .2);
$circle.y += (ty/dist) * ($circle.speed > 0 ? $circle.speed -= 0.005 : $circle.speed += .2);
}
this.ctx.arc($circle.x,$circle.y,$circle.size,0,Math.PI*2);
this.ctx.clearRect(0,0,this.ctx.canvas.width, this.ctx.canvas.height);
this.ctx.moveTo($circle.x + $circle.size, $circle.y); // so simply add 'rad' to the centerX
}
this.ctx.closePath();
this.ctx.fill();
}
closePath、は必要ありません。異なる色の各円の前にbeginPathが必要です。 – Blindman67