JS勾股定理算两坐标距离(直线像素距离,非地球经纬度)

JS勾股定理算两坐标距离(直线像素距离,非地球经纬度)

这玩意我写了不下5次了,脑子不行每次写都百度一圈费好大劲
这回写完CV一份过来,下回直接用!

function getDistance(a, b) {
    
    
      const b2: pos = {
    
     x: b.x - a.x, y: b.y - a.y }//计算坐标偏差值,让a点作为坐标原点
      return Math.sqrt(Math.pow(b2.x, 2) + Math.pow(b2.y, 2));//勾股算下直线距离 a²+b²=c² [你学废了吗^_^]
}

JS精简版

 const getDistance = (a, b) => {
    
     return Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2)) }

Typesctipt版

  interface pos {
    
     x: number, y: number }
  const getDistance = (a:pos, b:pos) => {
    
     return Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2)) }

另类算法

function getDistance (a, b) {
    
    
    const x = a.x - b.x;
    const y = a.y - b.y;
    return Math.hypot(x, y); // Math.sqrt(x * x + y * y);
}

猜你喜欢

转载自blog.csdn.net/cbaili/article/details/130257249