15,793,547 members
0.00/5 (No votes)
See more:
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:

------------------------------------------------------------------------
Posted
Updated 8-May-18 1:07am

## Solution 1

Comments
Maciej Los 8-May-18 15:40pm
Good advice!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Top Experts
Last 24hrsThis month
 Rick York 90 Chris Copeland 65 Dave Kreskowiak 40 Richard MacCutchan 20 KarstenK 20
 Andre Oosthuizen 200 Rick York 90 Maxim Kartavenkov 90 CPallini 68 Chris Copeland 65

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900