2017-10-15 81 views
0

我想畫出不同顏色的兩個矩形:借鑑不同顏色的畫布矩形

var canvas = document.getElementById('canvas'); 
var context = canvas.getContext('2d'); 
context.beginPath(); 
context.drawImage(this,0,0); 
context.beginPath(); 
context.rect(left1,top1,width1,height1); 
context.lineWidth = 8; 
context.strokeStyle = 'red'; 
context.stroke(); 
context.rect(left2,top2,width2,height2); 
context.lineWidth = 8; 
context.strokeStyle = 'green'; 
context.stroke(); 

但兩者出來相同的顏色(綠色,這是選擇的第二種顏色)。

我想stroke不會做我所期望的。

有人可以請解釋我在這裏錯過了什麼?

謝謝。

回答

1

的技巧是,你只需要創建第二方之前調用context.beginPath()

雖然沒有嚴格要求,你應該也完全context.closePath()關閉您的路徑,以及(這是前context.stroke()稱爲)。

我已經添加了兩個context.beginPath()context.closePath()下面的例子:

var canvas = document.getElementById('canvas'); 
 
var context = canvas.getContext('2d'); 
 
//context.beginPath(); 
 
//context.drawImage(this, 0, 0); 
 
context.beginPath(); 
 
context.rect(30, 30, 30, 30); /* Modified */ 
 
context.lineWidth = 8; 
 
context.strokeStyle = 'red'; 
 
context.closePath(); 
 
context.stroke(); 
 
context.beginPath(); /* Added */ 
 
context.rect(80, 30, 30, 30); /* Modified */ 
 
context.lineWidth = 8; 
 
context.strokeStyle = 'green'; 
 
context.closePath(); 
 
context.stroke();
<canvas id="canvas" width="150" height="100" style="border:1px solid #000000;"> 
 
</canvas>

希望這有助於! :)

+0

我認爲你對'closePath'及其功能感到困惑。它不是一個* end path *,而只是一個lineTo最後一個moveTo點,用於轉換一個封閉的路徑(比如三角形中的兩條線)。一個矩形已經是一個閉合的形狀,所以'closePath'在這裏完全沒用。 – Kaiido

1

看看下面這個例子

var c = document.getElementById("myCanvas"); 
 
var ctx = c.getContext("2d"); 
 

 
// Red rectangle 
 
ctx.beginPath(); 
 
ctx.lineWidth = "6"; 
 
ctx.strokeStyle = "red"; 
 
ctx.rect(5, 5, 290, 140); 
 
ctx.stroke(); 
 

 
// Green rectangle 
 
ctx.beginPath(); 
 
ctx.lineWidth = "4"; 
 
ctx.strokeStyle = "green"; 
 
ctx.rect(30, 30, 50, 50); 
 
ctx.stroke();
<canvas id="myCanvas" width="300" height="150">