2011-12-09 54 views
3

我已经使用了clearRect函数,但没有看到多边形的等价物。我天真地试着:如何清除画布元素中的多边形区域?

ctx.fillStyle = 'transparent'; 
ctx.beginPath(); 
ctx.moveTo(0, 0); 
ctx.lineTo(100,50); 
ctx.lineTo(50, 100); 
ctx.lineTo(0, 90); 
ctx.closePath(); 
ctx.fill(); 

但是,这只是吸引透明区域,并没有什么已经存在的效果。有没有办法清除画布元素内的多边形区域?

回答

13

您可以使用compositing设置为'destination-out'此操作:

ctx.globalCompositeOperation = 'destination-out'; 
ctx.beginPath(); 
ctx.moveTo(0, 0); 
ctx.lineTo(100,50); 
ctx.lineTo(50, 100); 
ctx.lineTo(0, 90); 
ctx.closePath(); 
ctx.fill(); 

例子:

enter image description here

尝试在jsFiddle

+4

感谢乔纳斯!注意自我:为了达到你想要的效果,你需要一个不透明的填充颜色(没有alpha透明度)。 – Benjie

+0

谢谢@Benjie,您的评论完整答案,我很久以前就在寻找它。 –

+0

很好用 - 链接到[合成](https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation)已经移动 – TadLewis