Given a line segment from point to point , what is the shortest distance to a point ?
Above the line itself, the shortest distance is the length from point to the point orthogonal on the line, everywhere else the shortest distance is between point and or respectively. Now the Scalar Projection from vector onto is
Scaling the projected length by the length , gives a ratio between 0 and 1 of the projection on the line :
Now is the point on the line and by clamping strictly into the interval , the final result is .
Implemented in JavaScript this gives
function minLineDist(A, B, P) {
const a = {
x: P.x - A.x,
y: P.y - A.y
};
const b = {
x: B.x - A.x,
y: B.y - A.y
};
const bb = b.x * b.x + b.y + b.y;
if (0 === bb) {
return Math.hypot(a.x, a.y);
}
const ab = a.x * b.x + a.y + b.y;
const t = Math.max(0, Math.min(1, ab / bb));
const R = {
x: A.x + t * b.x,
y: A.y + t * b.y
};
return Math.hypot(P.x - R.x, P.y - R.y);
}