How do I delete a specific object on the HTML5 canvas?

3

Well, for example I have two rectangles drawn on canvas:

const canvas = document.getElementById('canvas')

const context = canvas.getContext('2d');

context.fillRect(20,20,150,100);
context.fillRect(300,300,150,100);
<canvas id="canvas" width="600px" height="600px"></canvas>

How can I delete a specific one? And how can I associate events with one of them in specific?

    
asked by anonymous 27.07.2018 / 16:33

1 answer

3
  

How can I delete a specific one? And how can I associate events with one of them in specific?

You can not. At least not easily. Think of the canvas as if it were the canvas in a program like Paint where you are painting pixels and there is no type of Ctrl + Z. Or as a paper full of paint in which you are drawing / painting. The only way to erase part of the drawing is by drawing something over it, even if that other thing is a white rectangle or something.

The context.fillRect method is just something that paints a lot of pixels inside the canvas. It could be implemented as a pair of for ties by traversing the corresponding area and setting the color of the pixels. The object equivalent to the rectangle does not even exist, either before, during, or after that call.

The best you can do is to invent objects that represent what is going to be drawn on the canvas and then use a function that draws such objects. And then you associate events with those objects. To delete one of them, you redraw the entire canvas from scratch without the object removed.

    
27.07.2018 / 18:50