【问题标题】:How to find coordinates of a point where 2 points and distance are given with Javascript如何找到用Javascript给出2点和距离的点的坐标
【发布时间】:2017-11-24 09:46:01
【问题描述】:

我有 2 个点 A1 (x1,y1) 和 A2 (x2,y2) 的坐标和距离 d。我需要在 A1 和 A2 定义的线性图上找到点 A3 的坐标,即到点 A2 的距离 d。我怎么能用 JavaScript 做到这一点? 类似于https://softwareengineering.stackexchange.com/questions/179389/find-the-new-coordinates-using-a-starting-point-a-distance-and-an-angle 其中角度已知

【问题讨论】:

    标签: javascript line points calculation


    【解决方案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);
    

    【讨论】:

      【解决方案2】:

      所以你必须从 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)
          }
      
      }
      

      【讨论】:

      • 另一张海报速度更快,而且我 - 作为非开发人员 - 发现它更容易理解。但是非常感谢您的替代和解释
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-20
      • 1970-01-01
      • 1970-01-01
      • 2022-11-02
      • 2012-06-13
      • 2016-02-03
      相关资源
      最近更新 更多