If I draw a new element in a canvas, how can I save the position of this element?
Context2d context = canvas.getContext2d();
context.setStrokeStyle("black");
context.arc(50, 50, 20, 0, Math.PI*2);
context.stroke();
Or moreover: how can I at all keep track of an element that I created? Is there some kind of stack I have to place them on? How can I save that just created circle element for later reference?
My understanding is that you aren’t saving objects to the canvas as much as you are altering the canvas. The circle you create exists only as a set of commands to the canvas and if you wish to store it somehow you’d need to create an object that stores it.
When I was learning canvas and wrote a little game I would create an object that had a
draw(Canvas c)function. Within the function I’d do whatever operations were necessary to draw on the canvas and also maintained X,Y coordinates that could be recalled later.Then from whatever class is modifying the canvas you can maintain a collection of
SomeDrawableObjectand know everything that has been put on the canvas and recall positions/colours/whatever you’ve stored in the class. You could potentially extend the class and the like as well.