How to clear a rectangle from an image in the canvas

I need to clear a rectangle drawn on an image in a canvas with damage to an existing image. I can draw small rectangular dots and clarify this. But the problem is, when I clear the rectangle, it remains a white little patch in the image.

Can someone tell me how to clear the rectangle from the image without damaging the existing image.

I used the following methods to clear rectangles but didn't work.

1) context.fillStyle ="white";

2) context.clearRect(xCoordinate, yCoordinate, 10, 08);

Thanks in advance!

+3


source to share


3 answers


Canvas doesn't work that way. It is one layer and also transparent by default. So with that in mind, you could achieve what you want by simply giving the canvas element a CSS background. This way, anything you paint over that background can be easily removed and the background will show.

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

      



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

+2


source


There is one thing you can do.

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

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

      



and draw a rectangle.

When clearing the rectangle, just put the image data back in like this:

context.putImageData(imgData, xCoordinate, yCoordinate);

      

+1


source


I suggest using two canvas elements on top of each other. This way you can have the original image on the bottom canvas with a low zIndex, and the top one with a high zIndex can be used to paint / clear whatever is needed. This is a common practice and you will get better performance for fuller animations.

0


source







All Articles