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
Here is the approach taken from Wikipedia article Distance from a point to a line (Line defined by two points)
var Dx = x2 - x1;
var Dy = y2 - y1;
var d = Math.abs(Dy*x0 - Dx*y0 - x1*y2+x2*y1)/Math.sqrt(Math.pow(Dx, 2) + Math.pow(Dy, 2));
where (x0,y0) is your Point coordinates and your Line is ((x1,y1),(x2,y2)) However, this does not checks for boundaries of the line, so I had to add another check for it.
function inBox(x0, y0, rect) {
var x1 = Math.min(rect.startX, rect.startX + rect.w);
var x2 = Math.max(rect.startX, rect.startX + rect.w);
var y1 = Math.min(rect.startY, rect.startY + rect.h);
var y2 = Math.max(rect.startY, rect.startY + rect.h);
return (x1 <= x0 && x0 <= x2 && y1 <= y0 && y0 <= y2);
}
Where your Line defined as rectangle. Hope this helps.