2017-09-08 8 views
0

このループで作成された各円にそれぞれの色を割り当てたいとします。今では、すべての$ 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(); 
      } 
+0

closePath、は必要ありません。異なる色の各円の前にbeginPathが必要です。 – Blindman67

答えて

0

あなたは、彼らが現在のパスに関連付けられているとして、各fillStyleまたはstrokeStyle操作のための新しいパスを開始する必要があり、新しいパスは、各サークルのために作成されるので、そう簡単にループ内でこれらのメソッドを移動しますおよび充填操作。

パスは1回クリアされ、繰り返しごとに新しいアークが追加されます。キャンバスは消去されますが、パスは削除され、新しい塗りつぶしスタイルが適用されるため、パス上のすべての円は最後の塗りつぶしスタイルを使用して再描画されます。

キャンバスもクリアされていますが、ここでは不要です(パスがクリアされていないので、あまり明白ではありませんので、すべての円は上に述べたように再描画されます)。アニメーションなら何でも描画される目標です。

の前にmoveTo()を呼び出すか、無意味です。新しいパスが作成されているので、実際には必要ではありませんが、そこに残しました。

// clearRect moved out of loop: 
this.ctx.clearRect(0, 0, this.ctx.canvas.width, this.ctx.canvas.height); 

//this.ctx.beginPath(); // move inside loop 
for (var i = 0; i < this.circles.length; i++) { 
    this.ctx.beginPath(); // here 

    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); 
    } 

    // use moveTo OP before adding the arc() 
    this.ctx.moveTo($circle.x + $circle.size, $circle.y); 
    this.ctx.arc($circle.x, $circle.y, $circle.size, 0, Math.PI * 2); 

    this.ctx.fill();  // here 
} 
//this.ctx.closePath(); // not needed for fill 
//this.ctx.fill();  // move inside loop 
+0

私のためにそれをクリアしてくれてありがとう! –

関連する問題