{{ message }}

Instantly share code, notes, and snippets.

# mattdesl/point-to-line-2d.js

Created Mar 22, 2018
2D Point to Line Segment distance function
 // Taken From: // https://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment function sqr (x) { return x * x; } function dist2 (v, w) { return sqr(v - w) + sqr(v - w); } // p - point // v - start point of segment // w - end point of segment function distToSegmentSquared (p, v, w) { var l2 = dist2(v, w); if (l2 === 0) return dist2(p, v); var t = ((p - v) * (w - v) + (p - v) * (w - v)) / l2; t = Math.max(0, Math.min(1, t)); return dist2(p, [ v + t * (w - v), v + t * (w - v) ]); } // p - point // v - start point of segment // w - end point of segment function distToSegment (p, v, w) { return Math.sqrt(distToSegmentSquared(p, v, w)); } module.exports = distToSegment; module.exports.squared = distToSegmentSquared;

### pjbaron commented Jan 22, 2020 • edited

 Handy snippet thanks! Here's the same thing modified to reuse partial results and accept data structures instead of lists: `````` function dist(point, x, y) { var dx = x - point.x; var dy = y - point.y; return Math.sqrt(dx * dx + dy * dy); } `````` `````` // point - { x, y } // line - { sx, sy, ex, ey } function distToSegment(point, line) { var dx = line.ex - line.sx; var dy = line.ey - line.sy; var l2 = dx * dx + dy * dy; if (l2 == 0) return this.dist(point, line.sx, line.sy); var t = ((point.x - line.sx) * dx + (point.y - line.sy) * dy) / l2; t = Math.max(0, Math.min(1, t)); return this.dist(point, line.sx + t * dx, line.sy + t * dy); } ``````