Here's my 2-cents:
What you’re suggesting is a lot like using quad-tree hit testing:
http://gamedev.tutsplus.com/tutorials/implementation/quick-tip-use-quadtrees-to-detect-likely-collisions-in-2d-space/
Your grid is like Quad-tree in that you’re seeking to generate a list of lines that are present in the target area and eliminate lines that don’t exist in the target area.
As such, your grid provides a way to initially focus the hit-test.
After initial focus, you will still need to check each line in the focus list to see if the click did hit any line(s).
I can’t say whether this initial focus is faster than alternative methods of hit-testing lines.
I suspect if the canvas is large and there are many lines, your grid-focus might have benefit.
I guess you could try using your idea [versus or in combination with] the more traditional alternatives below.
Alternatives:
As @Ken-AbdiasSoftware says in his link, you can hit-test using context.isPointInStroke and context.isPointInPath. These 2 existing hit tests are fast and efficient.
These hit-testing methods are available in most modern browsers that support canvas and are [likely] optimized by the browser.
IE supports context.isPointInPath but does not yet support context.isPointInStroke.
For IE, you could "cheat" and use context.isPointInPath by converting each line into a very skinny closed path.
Or for IE, a fast, but memory intensive alternative for line hit-testing could be:
- Clear the canvas,
- Draw one line on the canvas,
- Get an array of the RGBA pixel data with context.getImageData
- Save a new sub-array of just the pixel alpha values (save just the “A” out of the “RGBA”).
- Importance: The new alpha-array will have values>0 where this particular line exists.
- Repeat at #1 for all the other lines.
Then you can "hit-test" each line by checking its alpha-array at any specified x/y coordinate.
If the alpha-array at the specified coordinate is >0, the line exists at that pixel.
There is a variation of this approach that uses less memory but uses more processing.
For any line, there is more empty space on the canvas than “lined” space.
You might have an array containing only those pixel positions that were >0.
Then do the hit-testing by scanning the array to determine if the specified x/y coordinate is in the array.