19

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?

djvg
  • 11,722
  • 5
  • 72
  • 103
some student
  • 371
  • 1
  • 2
  • 8
  • Just store them in a variable whenever you draw? – ide Feb 28 '11 at 21:25
  • Duplicate of [Find current point on path for HTML Canvas context?](http://stackoverflow.com/questions/4577410/find-current-point-on-path-for-html-canvas-context); I wish this were possible, but it's not without wrapping the canvas context in a wrapper that tracks this. – Phrogz Feb 28 '11 at 23:18
  • see https://bugzilla.mozilla.org/show_bug.cgi?id=644633 – string QNA Mar 15 '13 at 15:36
  • [Path2D](https://developer.mozilla.org/en-US/docs/Web/API/Path2D) could be interesting, also see [here](https://stackoverflow.com/a/28913470). – djvg Apr 12 '21 at 10:40

2 Answers2

9

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.

Loktar
  • 34,764
  • 7
  • 90
  • 104
9

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.

Luis Rosety
  • 396
  • 4
  • 10
  • 2
    This don't answer the question. On the contrary, this just describe the problem... **`:(`** – Aacini Oct 15 '21 at 15:35