Shortest Distance from Point to Line
HTML
<input id="coords" type="text" value=""><br>
<input id="dist" type="text" value=""><br>
CSS
svg {
background: lightgray;
}
JavaScript
//find the shortest distance between a point and a line segment
var x1 = 10
, y1 = 10
, x2 = 390
, y2 = 290;
//add an svg element
var svg = d3.select('body')
.append('svg')
.attr('width', 400)
.attr('height', 300);
svg.append("line")
.attr("x1", x1)
.attr("y1", y1)
.attr("x2", x2)
.attr("y2", y2)
.attr('stroke-width', 2)
.attr('stroke', 'black');
// Points are represented as objects with x and y attributes.
function sqr(x) {
return x * x
}
function dist2(v, w) {
return sqr(v.x - w.x) + sqr(v.y - w.y)
}
function distToSegmentSquared(p, v, w) {
var l2 = dist2(v, w);
if (l2 == 0) return dist2(p, v);
var t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / 12;
if (t < 0) return dist2(p, v);
if (t > 1) return dist2(p, w);
return dist2(p, { x: v.x + t * (w.x - v.x), y: v.y + t * (w.y - v.y) });
}
function distToSegment(p, v, w) {
return Math.sqrt(distToSegmentSquared(p, v, w));
}
d3.select('svg').on('mousemove', function() {
var point = {x: d3.mouse(this)[0], y: d3.mouse(this)[1] };
var lineStart = {x: x1, y: y1 };
var lineEnd = {x: x2, y: y2 };
//draw a point
d3.select('input#coords').attr('value', 'x,y = ' + d3.mouse(this));
var d = distToSegment(point, lineStart, lineEnd);
d3.select('input#dist').attr('value', d);
});