MTplus
MTplus

Reputation: 2391

move, delete and retrieve added rectangles positions in a HTML5 canvas

I have this code below to add a rectangle to a canvas, I have some questions regarding this.

Upvotes: 1

Views: 2643

Answers (1)

robertc
robertc

Reputation: 75707

Is it possible to move the added rectangle after it has been created?

No, once drawn it is just pixels, there is no 'rectangle object' in the canvas. The usual approach to 'moving' a shape in canvas is to clearRect() (or the whole canvas) and then fillRect() in a slightly different position in a requestAnimationFrame controlled loop.

Is it possible to delete a rectangle that has been added?

As long as you've stored the location where you drew it, you can clearRect(). Note that this clears an area of pixels, not an object - the results of previous drawing operations will not automatically reappear.

Can I retrieve all added rectangles positions (x, y, width and height) after I have added a bunch of rectangles and lets say by click of a button?

No. The canvas does not store drawn objects, only pixel image data. If you want to keep track of the objects that have been drawn then you have to do that yourself. If you want to manipulate shapes instead of pixels then there are libraries like fabric.js which add an object manipulation layer on top of canvas, or you can use an svg element instead which will let you create graphics with normal DOM methods.

Upvotes: 4

Related Questions