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

如何查找未旋转矩形上距离给定点最近的边

轴对齐矩形最近边查找实现

给定无旋转的轴对齐矩形rect,坐标格式为((left, top), (bottom, right)),以及坐标为(x, y)的点point,实现方法返回距离点最近的边标识,取值为"top"(顶边)、"bottom"(底边)、"left"(左边)、"right"(右边)之一。

实现逻辑

轴对齐矩形的四条边分别平行于x轴和y轴,点到对应边的垂直距离只需要计算单坐标差的绝对值即可,不需要套用复杂的通用点到直线距离公式:

  • 点到顶边距离:Math.abs(point.y - rect[0][1])
  • 点到底边距离:Math.abs(point.y - rect[1][0])
  • 点到左边距离:Math.abs(point.x - rect[0][0])
  • 点到右边距离:Math.abs(point.x - rect[1][1])

算出四个距离后取最小值,返回最小值对应的边即可。如果出现点到两条边距离相等的场景(比如点在矩形某一个角的45度方向上),可以按业务需求调整返回优先级,下面的实现默认优先级为顶边 > 底边 > 左边 > 右边。

完整代码

function findClosestEdge(rect, point) {
    // 解构取出矩形边界值
    const [[left, top], [bottom, right]] = rect;
    const { x, y } = point;

    // 计算到四条边的垂直距离
    const distToTop = Math.abs(y - top);
    const distToBottom = Math.abs(y - bottom);
    const distToLeft = Math.abs(x - left);
    const distToRight = Math.abs(x - right);

    // 匹配最小距离对应的边
    const minDistance = Math.min(distToTop, distToBottom, distToLeft, distToRight);
    if (minDistance === distToTop) return "top";
    if (minDistance === distToBottom) return "bottom";
    if (minDistance === distToLeft) return "left";
    return "right";
}

该实现同时兼容点在矩形内部、矩形外部的所有场景,垂直距离计算不受点和边的相对位置影响。

内容的提问来源于stack exchange,提问作者Sanjay Verma

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 22:27:31