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

如何使用JavaScript计算矩形区域内两点的直线最短距离?

计算两点间直线最短距离的JavaScript方案

计算两点间的直线最短距离,用欧几里得距离公式就能解决,公式如下:

距离 = √[(x₂ - x₁)² + (y₂ - y₁)²]

对应到JavaScript里,可以这样实现:

代码示例

// 定义给定的两点坐标
const currentPosition = { x1: 100, y1: 100 };
const target = { x2: 213, y2: 187 };

// 封装计算距离的函数
function getStraightDistance(pointA, pointB) {
  const dx = pointB.x2 - pointA.x1;
  const dy = pointB.y2 - pointA.y1;
  // 用Math.sqrt开平方,Math.pow计算平方,也可以用**运算符替代Math.pow
  return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
}

// 执行计算并输出结果
const distance = getStraightDistance(currentPosition, target);
console.log(distance); // 输出约139.77

如果不需要封装函数,直接计算也可以:

const x1 = 100, y1 = 100;
const x2 = 213, y2 = 187;

const distance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
console.log(distance);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 17:22:01