How to get a link to old generated elements in HTML Canvas?

Take a look at this example:

var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); // First rectangle created ctx.fillRect(20,20,150,100); // Second rectangle created ctx.fillRect(20,150,150,100); // Third rectangle created ctx.fillRect(20,300,150,100); 

Here I created three rectangles. After creating the third rectangle, I want to rotate the first rectangle. How to get a link to the first rectangle now?

0
source share
4 answers

A canvas is just a foggy grid of pixels. He does not understand what forms were painted on him. Your code (or the library used by your code) should keep track of the shapes you drew.

Instead, it sounds like you want the library to create a scene graph such as EaselJS , Paper.js or KineticJS . These libraries will maintain a data structure that keeps track of which shapes were drawn on the canvas, and then they will redraw them when you want to manipulate these shapes.

+1
source

You do not get a link to a rectangle or something with a canvas. All you have is a canvas with context. What you can draw on. Period.

If you want to move the first rectangle, clear it (using clearRect ) and redraw the new one.

+4
source

The canvas itself is just pixels. He knows how to draw rectangles, but does not make them layered.

To quote Simon Sarris :

HTML5 Canvas is just a drawing surface for a bitmap. You created (Tell me the color and thickness of the line), draw this thing, and then the Canvas does not know about it: it does not know where it is or what it is, it's just pixels. If you want to draw rectangles and ask them to move or be selected, then you must encode everything from scratch, including the code, to remember that you drew them.

The one exception is the isPointInPath method, but it has limitations.

However, there are some libraries that provide an object-oriented interface for Canvas. For example Fabric.js or KineticJS . They remember that you draw as objects (rectangles, circles, etc.), and you can stack them on top of each other, move around and add mouse / touch events. Very similar to the DOM.

+2
source

Drawing functions such as fillRect() do not return anything (returns void).

This means that it simply displays pixels, it does not create a rectangle object and does not return it. You will need to save the rectangular coordinates yourself.

+1
source

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


All Articles