问题
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