Translate Coordinates Relative To Line Segment
I need to write a function (in Javascript) that accepts the endpoints of a line segment and an additional point and returns coordinates for the point relative to the start point. S
Solution 1:
I took a different approach, by combining two functions:
- To get yp' I find the intersection point using the answer from here: Perpendicular on a line from a given point
- To get xp' I calculate the distance between (xp, yp) and the line, using the equation from here: https://en.wikipedia.org/wiki/Distance_from_a_point_to_a_line
Not the most elegant solution, but it seems to work.
Resulting code https://jsfiddle.net/qke0m4mb/
functionperpendicular_coords(x1, y1, x2, y2, xp, yp) {
var dx = x2 - x1,
dy = y2 - y1;
//find intersection point var k = (dy * (xp-x1) - dx * (yp-y1)) / (dy*dy + dx*dx);
var x4 = xp - k * dy;
var y4 = yp + k * dx;
var ypt = Math.sqrt((y4-y1)*(y4-y1)+(x4-x1)*(x4-x1));
var xpt = distance(x1, y1, x2, y2, xp, yp);
return [xpt, ypt];
}
// Distance of point from linefunctiondistance(x1, y1, x2, y2, xp, yp) {
var dx = x2 - x1;
var dy = y2 - y1;
returnMath.abs(dy*xp - dx*yp + x2*y1 - y2*x1) / Math.sqrt(dy*dy + dx*dx);
}
Post a Comment for "Translate Coordinates Relative To Line Segment"