Let\'s say I have a line drawn as so in HTML5 Canvas:
...
ctx.beginPath();
ctx.moveTo(x,y);
ctx.lineTo(x1,y1);
ctx.closePath();
...
I want
The first step is to find the normal projection of the point onto the line. This is actually quite simple: take the distance from point 1 to the target, and point 2 to the target, and call them D1 and D2 respectively. Then calculate D1+(D2-D1)/2
. This is the distance to the projected point on the line from point 1.
You can now find that point, and get the distance from that point to the target. If the distance is zero, then the target is exactly on the line. If the distance is less than 5, then the target was less than 5px away, and so on.
EDIT: A picture is worth a thousand words. Here's a diagram:
(source: adamhaskell.net)
(In hindsight, probably should have made those circles a different colour... Also, the purple line is supposed to be perpendicular to line AB. Blame my terrible aim with the blue line!)