How do you clear a polygon shaped region in a canvas element?

假装没事ソ 提交于 2020-01-23 01:33:06

问题


I've used the clearRect function, but didn't see an equivalent for polygons. I naively tried:

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();

But that just draws a transparent region, and doesn't have an effect on what's already there. Is there a way to clear polygon regions inside of the canvas element?


回答1:


You can use compositing with the operation set to 'destination-out' for this:

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();

Example:

Try it on jsFiddle



来源:https://stackoverflow.com/questions/8445668/how-do-you-clear-a-polygon-shaped-region-in-a-canvas-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!