I am drawing lines using Canvas (HTML 5), since lines/shapes are not stored as objects in Canvas, I cannot attach unique events to it (eg onmouseclick)
I wish to attach a onmouseover event to a line, is it possible by getting to know if the mouse if over a particular line (using its 2 X and 2 Y co-ordinates) in Canvas using Javascript. Would this work for different line widths (eg: 2,5 pixels)
Want to avoid using SVG as the entire project is built on Canvas
Please advise.
Advertisement
Answer
You would need to use math formulas to calculate the area of the line and whether a certain point intersects with it.
Here’s a basic example:
- Find mouse coordinates relative to position of the canvas (How to find mouse pos on element)
- Calculate whether mouse x/y is inside some rectangle (Point in rectangle formula)
- Done.