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.