Ana*_*ate 86 javascript canvas
我有画布绘图选项卡,并希望lineWidth基于两个最后mousemove坐标更新之间的距离.我将自己进行距离到宽度的平移,我只需要知道如何获得这些点之间的距离(我已经有了这些指针的坐标).
Igo*_*vić 186
你可以用毕达哥拉斯定理来做到这一点
如果你有两个点(x1,y1)和(x2,y2)那么你可以计算x的差异和y的差异,让我们称它们为a和b.

var a = x1 - x2;
var b = y1 - y2;
var c = Math.sqrt( a*a + b*b );
// c is the distance
Run Code Online (Sandbox Code Playgroud)
eks*_*akt 22
http://en.wikipedia.org/wiki/Euclidean_distance
如果您有坐标,请使用公式计算距离:
var dist = Math.sqrt( Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2) );
Run Code Online (Sandbox Code Playgroud)
如果您的平台支持**运营商,您可以改为使用:
const dist = Math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2);
Run Code Online (Sandbox Code Playgroud)
这是一种快速查找(x1, y1)和之间距离的方法(x2, y2)
const distance = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);
Run Code Online (Sandbox Code Playgroud)
这是一个简短的可运行演示:
const distance = (x1, y1, x2, y2) => Math.hypot(x2 - x1, y2 - y1);
Run Code Online (Sandbox Code Playgroud)
要找到2点之间的距离,您需要在宽和高等于垂直和水平距离的直角三角形中找到斜边的长度:
Math.hypot(endX - startX, endY - startY)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
91371 次 |
| 最近记录: |