javascriptgeometryhtml5-canvasdistancesnapping

Snapping a line to a specified distance


I'm drawing a ton of lines and points onto a JavaScript canvas. When the user clicks, it adds a point, and a preview with a connection to the next point.

Example image:

Drawing with canvas

In this image the user has clicked three times, creating the three dark green points. Right now the user is hovering 28 px away from the last clicked point, creating the light green connection, point, and the black box that tells the distance.

Now I want to snap the light green point to 28px. How might I go about doing that? I want to give it a threshold of, say, 10px, and have it snap if it's within that threshold. I know that there's a good way to do this mathematically, but I haven't the knowledge to figure it out.

Thanks for the help!


Solution

  • Check the distance during mouse moving (X_Current is current mouse position, X_0 is last point position). Replace 28 and 10 constants by distance and threshold:

    Squared_Distance = (X_Current-X_0)*(X_Current-X_0) + (Y_Current-Y_0)*(Y_Current-Y_0)
    if ((Squared_Distance >= (28 - 10)*(28 - 10)) &&  (Squared_Distance <= (28 + 10)*(28 + 10)))
      then snap it
    

    Position of new point at 28px distance:

    Curr_Distance = Sqrt(Squared_Distance) // assert <> 0
    Dir_X = (X_Current-X_0) / Curr_Distance
    Dir_Y = (Y_Current-Y_0) / Curr_Distance
    P28_X = X0 + 28 * Dir_X
    P28_Y = Y0 + 28 * Dir_Y