2016-02-26 66 views
4

我想知道如果下面的代碼產生適當的行爲。我覺得左上角的廣場應該仍然是綠色的。也就是說,如果我裁剪一個區域,十次還原,然後在第二個區域中繪製,則畫布在兩個區域中繪製。爲什麼?HTML5 Canvas裁剪不正確?

https://jsfiddle.net/s6t8k3w3/

var my_canvas = document.getElementById('canvas'); 
var ctx = my_canvas.getContext("2d"); 

//Make Clipping Path 1 
ctx.save(); 
ctx.rect(20, 20, 100, 100); 
ctx.clip(); 

//Fill Background with Green 
ctx.fillStyle = 'rgba(0,255,0,1)'; 
ctx.fillRect(0, 0, my_canvas.width, my_canvas.height); 
//Close Clipping Path 1 
ctx.restore(); 

//Open Clipping Path 2 
ctx.save(); 
ctx.rect(50, 50, 100, 100); 
ctx.clip(); 

//Fill background with Blue 
ctx.fillStyle = 'rgba(0,0,255,1)'; 
ctx.fillRect(0, 0, my_canvas.width, my_canvas.height); 

//Draw Line 
ctx.beginPath(); 
ctx.moveTo(0, 0); 
ctx.lineTo(500, 500); 
ctx.stroke(); 

//CloseClipping Path 2 
ctx.restore(); 
+1

在每個單獨的路徑命令集之前使用'ctx.beginPath',否則隨後的'stroke/fill'會重繪自上次beginPath以來的所有內容。 – markE

回答

2

你不是真正打開第二個剪輯路徑與第二ctx.save();要做到這一點,你需要撥打ctx.beginPath()

+2

是的:也許是[概念驗證](https://jsfiddle.net/m1erickson/q3geoefe/) – markE

+0

非常感謝你們倆。很明顯,我必須更好地理解這個主題!顯然,這工作! – matt