获取画布上两点之间的距离 [英] Get distance between two points in canvas

查看:1341
本文介绍了获取画布上两点之间的距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have canvas drawing tab and want lineWidth to be based on distance between two last mousemove coordinate updates. I will make translation of distance to width myself, I just need to know how to get distance between those points (I already have coordinates of those pointes).

推荐答案

您可以使用pythagoras定理

You can do it with pythagoras theorem

如果您有两个点(x1,y1)和(x2,y2)
你可以计算x的差值和y的差值,让他们称为a和b。

If you have two points (x1, y1) and (x2, y2) then you can calculate the difference in x and difference in y, lets call them a and b.

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

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

// c is the distance

将是

var d = Math.sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) );

更新

...感谢 Jonas 稍微最小化的方式:(注意 - 这将改变原始变量的值)

...thanks to Jonas for this slightly minimized way: (caution - this will change the values of your original variables)

var d = Math.sqrt( (x2-=x1)*x2 + (y2-=y1)*y2 );

这篇关于获取画布上两点之间的距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆