向量投影-计算点到直线的垂足

该文章详细描述了一个JavaScript函数,用于计算给定点A、B、C构成的线段上的垂足以及垂足到线段的距离。方法涉及向量运算、投影和近似判断。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 /**
   * 计算垂足
   * @param {point} A 
   * @param {point} B 
   * @param {point} C 
   * @returns 
   */
  projectFootPoint(A, B, C) {
    //中点
    const centerPoint = {
      x: (A.x + B.x) / 2,
      y: (A.y + B.y) / 2
    }
    //向量
    const AB = {
      x: B.x - A.x,
      y: B.y - A.y
    }
    const AC = {
      x: C.x - A.x,
      y: C.y - A.y
    }
    //计算向量AB模长
    const lengthAB = Math.sqrt(AB.x * AB.x + AB.y * AB.y)
    //半长
    const halfLength = lengthAB / 2
    //计算AB单位向量
    const _AB = {
      x: AB.x / lengthAB,
      y: AB.y / lengthAB
    }
    //计算AC在AB的投影长度
    const projection_length = AC.x * _AB.x + AC.y * _AB.y;
    //计算投影坐标
    const point = {
      x: _AB.x * projection_length + A.x,
      y: _AB.y * projection_length + A.y
    }
    //计算中点到垂点距离
    const centerLength = Math.sqrt(Math.pow(point.x - centerPoint.x, 2) + Math.pow(point.y - centerPoint.y, 2))
    //是否在线段上 (近似判断)
    const flag = Math.round(centerLength * 1000) / 1000 <= Math.round(halfLength * 1000) / 1000
    //计算垂足到线段距离
    if(!flag){
      console.log(centerLength - halfLength);
    }
    //计算垂距
    const length = Math.sqrt(Math.pow(point.x - C.x, 2) + Math.pow(point.y - C.y, 2))
    return {
      flag,  // 是否在线段
      point,  // 垂足
      length   // 垂距
    }
  },

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值