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

Using javascript, I drew some polygonal images on my canvas.

I would like, based on user events / clicks, to be able to clear a section of the canvas (one of these polygon images), which is irregular in shape and not a rectangle.

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

Can anyone think of how I can do this?

Essentially, I would like to make part of my canvas transparent, but this is not a rectangular shape ... As soon as I have a region defined with which I can fill () and stroke (), can I also clear () it ... I know that such a function is not available. What do people do to clean irregularly shaped sections ?

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

+3
source share
1 answer

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

See https://developer.mozilla.org/en/Canvas_tutorial/Compositing

I also created a demo at http://jsfiddle.net/alnitak/6ABp7/

The clipping path is part of the graphical state, so you can .save()previous state, set cropping, draw a few more things, and then the .restore()original state.

+6
source

All Articles