如何使用Javascript找到给定2个点和距离的点的坐标

4
2个回答

9
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);

2

假设您的点是一个具有x和y属性以及距离方法的Point类的对象,则需要从A1出发,按照A1和A2之间的距离+d的方向前往A2。

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类实现:
```python class Point: def __init__(self, x=0, y=0): self.x = x self.y = y
def __str__(self): return "({0}, {1})".format(self.x, self.y) ```
该类具有x和y属性,可以用来表示二维坐标系中的点。
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)
    }

}

1
另一位海报的速度更快,而作为非开发人员,我更容易理解。但是非常感谢提供的替代方案和解释。 - user24957

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接