Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a canvas-context's last point's coordinates

I want to create an arrowTo function with CanvasRenderingContext2D.prototype. To do that, I need to get the coordinates of the last point, e.g.

//... 
var ctx = someCanvas.getContext('2d');

ctx.moveTo(10,40);
//the coordinates of the last point are now (10,40)

ctx.lineTo(50,50);
//and now it's (50,50)

//...

How can I retrieve them?

like image 908
some student Avatar asked Feb 28 '11 21:02

some student


People also ask

How do I find coordinates on a canvas?

The dimension of the canvas is found using the getBoundingClientRect() function. This method returns the size of an element and its position relative to the viewport. The position of x-coordinate of the mouse click is found by subtracting the event's x position with the bounding rectangle's x position.

Where is the 0 0 coordinate of a canvas?

Canvas Coordinates The coordinate (0, 0) is at the upper-left corner of the canvas. Along the X-axis, values increase towards the right edge of the canvas.

Is point in path canvas?

The canvas isPointInPath() Method is used to check whether or not the specified point is contained in the current path. The isPointInPath() method returns true if the specified point is in the current path, otherwise false.


2 Answers

This is a property that canvas HAS STORED somewhere and it should be available from a property (likely) because it can be difficult tracking last point coordinates.
For example when you draw an arc

ctx.arc(xc, yc, radius, starting_angle, ending_angle); 

You don't have immediate information of the last point coordinates.
Of course this can be obtained in this case with

lastX = xc + radius*Math.cos(ending_angle);
lastY = yc + radius*Math.sin(ending_angle);   

But it is irritating needing to include those computations when we know that canvas does remember last point.
If after the arc instruction you add a

ctx.lineTo(x, y);  

And it does work. Therefore canvas has that last point stored somewhere and I can't understand why it is hidden for the programmer.

like image 171
Luis Rosety Avatar answered Oct 14 '22 13:10

Luis Rosety


You'd have to keep track of them yourself. Or do the unthinkable and override moveTo/lineTo to keep track of the last coords via CanvasRenderingContext2D.prototype.

like image 28
Loktar Avatar answered Oct 14 '22 11:10

Loktar