You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS实现:寻找矩形内点到最近边的邻近位置

问题需求

已知二维空间中构成矩形的四个顶点数组:

var corner1 = [x, y];
var corner2 = [x, y];
var corner3 = [x, y];
var corner4 = [x, y];

还有一个已确认在矩形内部的点(无需校验位置合法性):

var point = [x, y]

需用JavaScript实现功能:找到该点到矩形最近边的邻近位置(即该点在最近边上的投影点,示意图为矩形内部一点向四条边作垂线,取距离最短的垂线端点)。

实现思路
  • 从四个顶点生成矩形的四条边(每条边用两个端点表示)。
  • 计算内部点在每条边上的投影点(因点在矩形内,投影点必在边的线段范围内)。
  • 比较点到每个投影点的距离,取距离最小的投影点作为结果。
代码实现

辅助工具函数

// 计算向量点积
function dotProduct(v1, v2) {
  return v1[0] * v2[0] + v1[1] * v2[1];
}

// 计算两点间距离的平方(避免开根号,提升性能)
function distanceSquared(p1, p2) {
  const dx = p1[0] - p2[0];
  const dy = p1[1] - p2[1];
  return dx * dx + dy * dy;
}

// 计算点p在线段ab上的投影点
function projectPointToSegment(p, a, b) {
  const ab = [b[0] - a[0], b[1] - a[1]];
  const ap = [p[0] - a[0], p[1] - a[1]];
  const t = dotProduct(ap, ab) / dotProduct(ab, ab);
  return [a[0] + t * ab[0], a[1] + t * ab[1]];
}

主函数

function findNearestEdgePoint(corners, point) {
  // 构建矩形的四条边
  const edges = [
    [corners[0], corners[1]],
    [corners[1], corners[2]],
    [corners[2], corners[3]],
    [corners[3], corners[0]]
  ];

  let nearestPoint = null;
  let minDistanceSq = Infinity;

  // 遍历每条边,找到最近的投影点
  for (const [a, b] of edges) {
    const projected = projectPointToSegment(point, a, b);
    const distSq = distanceSquared(point, projected);
    if (distSq < minDistanceSq) {
      minDistanceSq = distSq;
      nearestPoint = projected;
    }
  }

  return nearestPoint;
}

// 使用示例
const rectCorners = [[0, 0], [0, 10], [20, 10], [20, 0]];
const targetPoint = [5, 3];
const result = findNearestEdgePoint(rectCorners, targetPoint);
console.log(result); // 输出 [5, 0],对应到矩形下边的投影点
补充说明
  • 因输入点已确认在矩形内部,无需额外判断投影点是否超出边的范围。
  • 用距离平方做比较,省去开根号运算,计算效率更高。

内容的提问来源于stack exchange,提问作者A. Cheshirov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 09:50:42