Boriana Boriana - 1 year ago 37
Javascript Question

Is there a way to clear a non-rectangular area in a canvas element?

Using javascript, I've drawn several polygon images on my canvas.

I'd like to, based on user events/clicks, be able to clear a section of the canvas (one of those polygon images), which is an irregular shape, not a rectangle.

So, I cannot use clearRect() for my purpose.

Can anyone think of a way I can do that?

Essentially, I'd like to make a portion of my canvas transparent, but it is not a rectangular shape... Once I have an area defined with which I can fill() and stroke(), can I not also clear() it... I know that such a function is not available. What are folks doing to clear irregularly shaped sections?

I'm a little new to this, so apologies in advance if this sounds like a silly question.


Use ctx.clip() to define the current stroke as a clipping region.


I also created a demo at

The clipping path is part of the graphics state, so you can .save() the previous state, set clipping, draw some more stuff, and then .restore() the original state.