Here's an approach taken from a Wikipedia article Distance from a point to a line (a 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 ((x1, y1), (x2, y2)) However, this does not check the boundaries of the line, so I had to add one more check.
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); }
If your line is defined as a rectangle. Hope this helps.
source share