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?
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With