[英]Change canvas fillStyle in loop
我想將在此循環中創建的每個圓分配給其各自的顏色。 現在,盡管每個$ circle對象具有不同的顏色,但它們都被設置為相同的顏色。 我讀到我需要在下一個循環之前關閉路徑或填充,我非常確定我已經做到了,但是仍然沒有用。 我的代碼如下:
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();
}
您必須為每個fillStyle
或strokeStyle
操作綁定到當前路徑開始新路徑,因此只需在循環內移動這些方法即可為每個圓和fill操作創建新路徑。
現在發生的事情是清除路徑一次,然后在每次迭代中添加新的弧。 畫布已清除,但路徑未清除,並且具有新的填充樣式,因此使用最后的填充樣式重新繪制了路徑上的所有弧。
您還需要為此處的每次迭代清除畫布(這並不是很明顯(因為沒有清除路徑,因此如上所述重新繪制了所有的圓))-盡管如果動畫是目標,則可以在繪制任何內容之前調用它。
並且moveTo()
應該在arc()
之前調用,否則將毫無意義; 由於創建了新路徑,因此並不需要,但我將其留在了那里。
// 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.