我有2点A1(x1,y1)和A2(x2,y2)的坐标和距离d。我需要找到点A3的坐标,它是A1和A2定义的线性图上距离点A2的距离d。我怎么能用JavaScript做到这一点? 类似于https://softwareengineering.stackexchange.com/questions/179389/find-the-new-coordinates-using-a-starting-point-a-distance-and-an-angle 角度已知的地方
答案 0 :(得分:1)
var A1 = {
x : 2,
y : 2
};
var A2 = {
x : 4,
y : 4
};
// Distance
var d= 2;
// Find Slope of the line
var slope = (A2.y-A1.y)/(A2.x-A1.x);
// Find angle of line
var theta = Math.atan(slope);
// the coordinates of the A3 Point
var A3x= A2.x + d * Math.cos(theta);
var A3y= A2.y + d * Math.sin(theta);
console.log(A3x);
console.log(A3y);
答案 1 :(得分:1)
所以你必须从A1开始,然后沿A1和A2 + d的距离前往A2方向 假设您的点是具有x和y属性的Point类的对象,并且您可以执行此操作:
function move_to(origin, direction, dist){
let dx = direction.x - origin.x;
let dy = direction.y - origin.y;
let coef = dist / origin.distance(direction);
let x = origin.x + dx * coef;
let y = origin.y + dy *coef;
return new Point(x, y)
}
move_to(A1, A2, A1.distance(A2) + d)
如果您需要,这里是一个简单的Point类实现:
class Point {
constructor(x, y){
this.x = x;
this.y = y;
}
distance(point){
return Math.sqrt((this.x - point.x) ** 2 + (this.y - point.y) ** 2)
}
}