patorjk
patorjk

Reputation: 2182

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

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?

Upvotes: 3

Views: 4158

Answers (1)

Jonas
Jonas

Reputation: 128807

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:

enter image description here

Try it on jsFiddle

Upvotes: 15

Related Questions