How to delete a specific object in HTML5 canvas?

Asked

Viewed 1,777 times

3

Good, for example I have two rectangles drawn on the 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 only one specific? And how can I associate events to one specific event?

1 answer

3


How can I delete only one specific? And how can I associate events to one specific event?

You can’t. 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 like a paper full of ink on which you are drawing/painting. The only way to erase part of the drawing is to draw something else over it, even if that other thing is a white rectangle or something like that.

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.