我有一个画布绘制选项卡,希望线条宽度基于两个最后的mousemove坐标更新之间的距离。我将自己将距离转换为宽度,我只需要知道如何获取这些点之间的距离(我已经有这些点的坐标)。
我有一个画布绘制选项卡,希望线条宽度基于两个最后的mousemove坐标更新之间的距离。我将自己将距离转换为宽度,我只需要知道如何获取这些点之间的距离(我已经有这些点的坐标)。
var a = x1 - x2;
var b = y1 - y2;
var c = Math.sqrt( a*a + b*b );
// c is the distance
Math.hypot
是 ES2015 标准的一部分。在 MDN 文档 中也有一个很好的 polyfill 来实现此功能。Math.hypot(x2-x1, y2-y1)
。Math.hypot()
来计算距离。它大约慢了100倍。 - Markus Zellerhttp://en.wikipedia.org/wiki/Euclidean_distance
如果你已经有坐标,请使用这个公式来计算距离:
var dist = Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2) );
如果您的平台支持**
运算符,您可以使用它代替:
const dist = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
要找出两点之间的距离,你需要在一个直角三角形中找到斜边的长度,该三角形的底和高分别等于水平和垂直距离:
Math.hypot(endX - startX, endY - startY)
这里是一个简短的一行代码,用于计算点 (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}`)
我在制作东西时经常使用这个计算,所以我喜欢将它添加到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);
两个坐标点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 Simantovdiff
,因为平方一个数总会得到一个正数。如果 x1 - y1
是负数,(x1 - y1) ^ 2
仍然是正数。 - Radvylf Programs
x1 - x2, y1 - y2
或者x2 - x1, y2 - y1
有什么区别吗? - Rami Chasygov7 - 5 = 2
还是5 - 7 = -2
都不会有影响。-2 * -2 = 4
2 * 2 = 4
- rdmurphy