2017-07-18 16 views
-1

嗨,我想了解帆布的打開和關閉功能的要領。 我注意到的是當我只用一個開放和關閉功能的畫布爲2個獨立的對象一個矩形和一個半圓。顏色開始泄漏,如圖所示:帆布對象:JavaScript中的半圓漏色

figure 1:result noticed

我想到的是如下圖2.一個開閉帆布功能:

figure 2 result expected

的代碼如下

提到
var canvas = document.getElementById("myCanvas"); 
var ctx = canvas.getContext("2d"); 
ctx.beginPath(); 
ctx.rect(30, 30, 50, 60); 
ctx.fillStyle = "#FF0000"; 
ctx.fill(); 
ctx.closePath(); 

ctx.beginPath(); 
ctx.arc(350,200,20,0,Math.PI*2,false); 
ctx.fillStyle = "green"; 
ctx.fill(); 



ctx.closePath(); 
+3

STOP SHOUTING!它只會讓人變得憤怒,而不是想幫助你! –

+3

如果您將代碼移植到FORTRAN,那麼您也可以使用大寫。 – Bathsheba

+0

您提到的代碼不會生成第一個圖像。 –

回答

0

函數ctx.beginPath通過刪除所有現有路徑來創建新的路徑對象點和中風

如果隨後ctx.beginPath

該函數的功能ctx.closePath創建從添加到當前路徑以前ctx.moveToctx.beginPath是無關的ctx.beginPath功能和什麼也不做最後的點線ctx.closePath是同樣如下面ctx.lineTo

ctx.beginPath(); 
ctx.moveTo(100,100); 
ctx.lineTo(200,200); 
ctx.lineTo(100,200); 
ctx.lineTo(100,100); // back to start 

ctx.beginPath(); 
ctx.moveTo(100,100); 
ctx.lineTo(200,200); 
ctx.lineTo(100,200); 
ctx.closePath(); // does the same as ctx.lineTo(100,100); // back to start 

代碼中的一些註釋。

var canvas = document.getElementById("myCanvas"); 
var ctx = canvas.getContext("2d"); 
ctx.beginPath(); 
ctx.rect(30, 30, 50, 60); 
ctx.fillStyle = "#FF0000"; 
ctx.fill(); 
ctx.closePath(); // <<< Not needed as you have already called fill 

ctx.beginPath(); // <<< this deletes the previous path 
ctx.arc(350,200,20,0,Math.PI*2,false); 
ctx.fillStyle = "green"; 
ctx.fill(); 

ctx.closePath(); // <<< not needed