ChatGPT解决这个技术问题 Extra ChatGPT

获取画布中两点之间的距离

我有画布绘图选项卡,并希望 lineWidth 基于两个最后一次 mousemove 坐标更新之间的距离。我将自己将距离转换为宽度,我只需要知道如何获得这些点之间的距离(我已经有了这些点的坐标)。


T
Tony L.

你可以用毕达哥拉斯定理做到这一点

如果您有两个点 (x1, y1) 和 (x2, y2),那么您可以计算 x 的差和 y 的差,我们称它们为 a 和 b。

https://i.stack.imgur.com/Vrq80.png

var a = x1 - x2;
var b = y1 - y2;

var c = Math.sqrt( a*a + b*b );

// c is the distance

你可以缩短 var c = Math.sqrt(aa + bb);到 var c = Math.hypot(a,b);
a^2 + b^2 = c^2 斜边方程
如果你去 x1 - x2, y1 - y2x2 - x1, y2 - y1 有什么不同吗?
@RamzanChasygov 在这种情况下没有区别,因为每个值都是平方的!因此,订单是像 7 - 5 = 2 还是 5 - 7 = -2 都无关紧要。 -2 * -2 = 4 2 * 2 = 4
D
David Gee

请注意,Math.hypot 是 ES2015 标准的一部分。 MDN doc 上还有一个很好的 polyfill 用于此功能。

因此,获取距离变得像 Math.hypot(x2-x1, y2-y1) 一样简单。


当性能很重要时,我不建议使用 Math.hypot() 来计算距离。它慢了大约 100 倍。
这里解释了为什么 Math.hypot 更慢,主要是因为它会更准确。这对你来说可能很重要,也可能无关紧要。 stackoverflow.com/questions/3764978/…
b
bb216b3acfd8f72cbc8f899d4d6963

http://en.wikipedia.org/wiki/Euclidean_distance

如果您有坐标,请使用公式计算距离:

var dist = Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2) );

如果您的平台 supports the ** operator,您可以改用它:

const dist = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);

R
Richie Bendall

要找到 2 点之间的距离,您需要在宽度和高度等于垂直和水平距离的直角三角形中找到斜边的长度:

Math.hypot(endX - startX, endY - startY)

S
Symbolic

我倾向于在我做的事情中使用这个计算,所以我喜欢将它添加到 Math 对象中:

Math.dist=function(x1,y1,x2,y2){ 
  if(!x2) x2=0; 
  if(!y2) y2=0;
  return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1)); 
}
Math.dist(0,0, 3,4); //the output will be 5
Math.dist(1,1, 4,5); //the output will be 5
Math.dist(3,4); //the output will be 5

更新:

当您最终遇到类似于此的情况时,这种方法尤其令人高兴(我经常这样做):

varName.dist=Math.sqrt( ( (varName.paramX-varX)/2-cx )*( (varName.paramX-varX)/2-cx ) + ( (varName.paramY-varY)/2-cy )*( (varName.paramY-varY)/2-cy ) );

可怕的事情变得更易于管理:

varName.dist=Math.dist((varName.paramX-varX)/2, (varName.paramY-varY)/2, cx, cy);

D
Daniel

两个坐标x和y之间的距离! x1 和 y1 是第一个点/位置,x2 和 y2 是第二个点/位置!

函数 diff (num1, num2) { if (num1 > num2) { return (num1 - num2); } 其他 { 返回 (num2 - num1); } };函数 dist (x1, y1, x2, y2) { var deltaX = diff(x1, x2); var deltaY = diff(y1, y2); var dist = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));返回(分布); };


您应该使用 Math.abs 而不是 diff
您不需要使用 diff,因为对数字进行平方将始终产生正数。如果 x1 - y1 为负,(x1 - y1) ^ 2 仍为正。
C
Coder Gautam YT

这是一个快速的单线查找 (x1, y1)(x2, y2) 之间的距离

const distance = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1); 

这是一个简短的可运行演示:

常量距离 = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1); var x1 = 1 var y1 = 5 var x2 = 4 var y2 = 5 var d = distance(x1, y1, x2, y2) console.log(`(${x1}, ${y1}) 和 ( ${x2}, ${y2}) 是 ${d}`)