Skip to content Skip to sidebar Skip to footer

How To Clear Rectangle On Image In Canvas

I need to clear a rectangle Drawn on Image in Canvas with out damage existing image. I can draw small rectangle points and clear that out. But the problem is when I clear rectangle

Solution 1:

Canvas doesn't work that way. It's a single layer, its also transparent by default. So with that in mind, you might be able to achieve what you want by simply giving the canvas element a CSS background. That way anything you draw on top of that background can easily be removed and the background will show through.

#backed-canvas{
    background-image: url(http://www.placebear.com/300/200);
}

JSFiddle example: https://jsfiddle.net/yLf5erut/


Solution 2:

There is one thing you can do.

When create a rectangle on the canvas just get the image data like:

var imgData = context.getImageData(xCoordinate, yCoordinate, 10, 8);

and draw the rectangle.

When clearing out the rectangle just place then image data back like this:

context.putImageData(imgData, xCoordinate, yCoordinate);

Solution 3:

I suggest using 2 canvas elements one over another. So you can have the original image drawn on the bottom canvas with low zIndex, and the top one with highter zIndex can be used to draw / clear whatever needed. This is a common practice, and for more complecated animations you will end up with better performance.


Post a Comment for "How To Clear Rectangle On Image In Canvas"