在javascript中查找最接近某一点的行 [英] Finding the closest line to a point in javascript

查看:76
本文介绍了在javascript中查找最接近某一点的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一系列使用HTML Canvas绘制的线条,我试图找出哪条线最接近光标,以及然后用不同的颜色突出它。



结果不太正确,因为看起来我使用的公式没有考虑到这些线条的事实不是无限的。这是一个截图



你可以看到绿色示例线和红色一个被认为是最接近的,因为如果你想象它向下无限延伸,它将最接近光标。但是,显然光标正上方的线最近。我怎么能解释这个?



对于每一行,我执行以下操作来查找距离,然后找到所有距离中最短的,并突出显示红线。



公式:

 var dist = Math.abs(((x *(y2  - y1)) - (y *(x2  -  x1))+(x2 * y1) - (y2 * x1)))/ Math.sqrt(((y2  -  y1)^ 2)+((x2  -  x1)^ 2 )); 

其中(x,y)是光标位置,(x1,y1,x2,y2)是该行。



解释自维基百科



我的尝试:



-------------------- -------------------------------------------------- -

解决方案

参见语言不可知 - 点和线段之间的最短距离 - 堆栈O. verflow [ ^ ]。

Hi,

I have a series of lines drawn using HTML Canvas and I'm trying to figure out which of the lines is closest to the cursor, and then highlight it a different colour.

The results are not quite right, as it appears the formula I'm using doesn't take into consideration the fact that these lines aren't infinite. Here's a screenshot.

You can see the green example lines and the red one is being seen as the closest, because if you imagine it extending infinitely downward, it would be the closest to the cursor. However, clearly the line just above the cursor is closest. How can I account for this?

For each of the lines, I perform the following to find the distance, then find the shortest of all of the distances, and highlight the line red.

Formula:

var dist = Math.abs(((x * (y2 - y1)) - (y * (x2 - x1)) + (x2 * y1) - (y2 * x1))) / Math.sqrt(((y2 - y1) ^ 2) + ((x2 - x1) ^ 2));

Where (x, y) is the cursor position, and (x1, y1, x2, y2) is the line.

Interpreted from Wikipedia

What I have tried:

------------------------------------------------------------------------

解决方案

See language agnostic - Shortest distance between a point and a line segment - Stack Overflow[^].


这篇关于在javascript中查找最接近某一点的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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