2014-05-15 31 views
0

在HTML5畫布中,我試圖用另一個對象敲出一個對象,並敲擊此操作的最終產品。這可能嗎?我使用下面的代碼,但沒有成功:我如何撫摸被撞物體?

var tcan = document.getElementById('test'); 
var tctx = tcan.getContext('2d'); 

tctx.beginPath(); 

tctx.fillStyle = '#F00'; 
tctx.fillRect(0,0,70,70); 

tctx.globalCompositeOperation = "destination-out"; 

tctx.fillRect(20,20,70,70); 
tctx.closePath(); 

tctx.strokeStyle = '#FF0'; // expecting the final product to have a yellow stroke 
tctx.stroke(); 

回答

2

演示:http://jsfiddle.net/m1erickson/x8Maf/

enter image description here

您可以使用源頂上合成提請貴黃行程只有頂上現有的淘汰賽:

tctx.beginPath(); 

tctx.fillStyle = '#F00'; 
tctx.fillRect(0,0,70,70); 

// knock-out compositing 
tctx.globalCompositeOperation = "destination-out"; 

tctx.fillRect(20,20,70,70); 
tctx.closePath(); 

// composite where new drawings appear only where overlapping existing 
tctx.globalCompositeOperation = "source-atop"; 

tctx.strokeStyle = '#FF0'; // expecting the final product to have a yellow stroke 
tctx.lineWidth=2; 
tctx.strokeRect(20,20,70,70); 

// restore the default compositing 
tctx.globalCompositeOperation = "source-over"; 

一對夫婦的提示:

  • 如果您使用fillRect或strokeRect(這些命令自動爲您啓動beginPath),則不需要beginPath;

  • 所有畫布描邊在指定尺寸範圍內是半內半部分。所以fillRect(20,20,70,70)實際上會從19.50到20.50。

[加法回答:這裏是如何中風淘汰賽形狀。 ]

var tcan = document.getElementById('test'); 
var tctx = tcan.getContext('2d'); 

tctx.lineWidth=2; 
tctx.strokeStyle = '#FF0'; 

tctx.fillStyle = '#F00'; 
tctx.fillRect(50,50,70,70); 
tctx.strokeRect(50,50,70,70); 

// knock-out compositing 
tctx.globalCompositeOperation = "destination-out"; 

tctx.fillRect(70,70,70,70); 
tctx.closePath(); 

// composite where new drawings appear only where overlapping existing 
tctx.globalCompositeOperation = "source-atop"; 

tctx.lineWidth=4; 
tctx.strokeRect(70,70,70,70); 

// restore the default compositing 
tctx.globalCompositeOperation = "source-over"; 
+0

感謝您的提示,但是您提供的代碼不能按預期工作。筆畫僅在形狀的兩個內邊緣繪製,即使我將「lineWidth」增加到更大的值以便更好地看到效果。我也用'stroke()'替換了'.strokeRect()' - 無濟於事。 – user776686

+0

我以爲你想要在右下角的黃色筆畫?如果你想中風整個被淘汰的形狀,我已經爲我的答案添加了解決方案。 – markE

+0

非常感謝!你比在我的機器上啓動Illustrator更快......這正是我所追求的。 – user776686