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:
------------------------------------------------------------------------