How to delete, delete, delete or delete an image from an html canvas?

this.context.drawImage(myimage, 0, 0); 

Putting the image on the canvas is pretty well covered all over the Internet. But how to remove it after it?

+6
source share
3 answers

Option 1:
Draw a rectangle above it in the same color as the background.

Option 2 (works for a non-trivial background, but slower):
Get the pixel data from the canvas before drawing the image, and then redraw that pixel data to remove the image.

+4
source

A canvas is an immediate surface of a drawing. This means that you execute a command on it (drawImage or fillRect), and it executes this command, and does not give a damn about what has just been done. There is nothing to spoil.

It was difficult for you to find it, because there is no thing like a β€œdelete” for the canvas. All he knows is that he has some pixels of some color. He does not know where.

To simplify the bit, there are usually two ways:

  • Clear the entire canvas and paint again. EXCEPT a single image that you do not want to draw.
  • Use two canvases that have only an image and one with all other things. Clean this canvas with clearRect (0,0, width, height) and you're done.

In section 1, you will notice that you may have to start tracking what you draw on the canvas if you want some of them to be selectively deleted or moved. Customizing an object, or rather, rotating the canvas from the immediate drawing surface to a saved drawing surface, is what many canvas libraries do. If you want to do it yourself, I wrote some tutorails to help people get started.

If you want to look into libraries, take a look at easel.js . This is pretty trainable.

+10
source

So, I came up with a quick and easy way to clear my canvas. I just put the <canvas> tags between the <p> tags with an identifier, and every time I needed to clear my canvas, I just renamed the <p> tags, changing innerHTML , it works like a charm.

+2
source

Source: https://habr.com/ru/post/898175/


All Articles