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

141

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

7个回答

265
你可以使用勾股定理来计算。
如果你有两个点 (x1, y1) 和 (x2, y2),那么你可以计算 x 和 y 的差,我们称之为 a 和 b。 enter image description here
var a = x1 - x2;
var b = y1 - y2;

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

// c is the distance

39
你可以将代码:var c = Math.sqrt( aa + bb ); 简化为 var c = Math.hypot(a,b); - evgpisarchik
2
a^2 + b^2 = c^2 是勾股定理的公式。 - Kad
你用 x1 - x2, y1 - y2 或者 x2 - x1, y2 - y1 有什么区别吗? - Rami Chasygov
6
在这种情况下没有区别,因为每个值都被平方了!所以无论顺序是 7 - 5 = 2 还是 5 - 7 = -2 都不会有影响。 -2 * -2 = 4 2 * 2 = 4 - rdmurphy

188
请注意,Math.hypot 是 ES2015 标准的一部分。在 MDN 文档 中也有一个很好的 polyfill 来实现此功能。
因此,获取距离变得像这样简单:Math.hypot(x2-x1, y2-y1)

3
当性能很重要时,我不建议使用Math.hypot()来计算距离。它大约慢了100倍。 - Markus Zeller
1
以下是Math.hypot函数较慢的原因解释,基本上是因为它会更精确。这可能对您有所影响,也可能没有。https://dev59.com/LW865IYBdhLWcg3wivKj - RayB

36

15

要找出两点之间的距离,你需要在一个直角三角形中找到斜边的长度,该三角形的底和高分别等于水平和垂直距离:

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

7

这里是一个简短的一行代码,用于计算点 (x1, y1) 和点 (x2, y2) 之间的距离。

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

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

const distance = (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(`The distance between (${x1}, ${y1}) and (${x2}, ${y2}) is ${d}`)


3

我在制作东西时经常使用这个计算,所以我喜欢将它添加到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);

3

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

function diff (num1, num2) {
  if (num1 > num2) {
    return (num1 - num2);
  } else {
    return (num2 - num1);
  }
};

function 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));
  return (dist);
};


你应该使用 Math.abs 而不是 diff - Moshe Simantov
6
不需要使用 diff,因为平方一个数总会得到一个正数。如果 x1 - y1 是负数,(x1 - y1) ^ 2 仍然是正数。 - Radvylf Programs

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接