Search code examples
algorithmhit

How can I tell if the mouse pointer is inside a path defined by Bezier curves and lines?


I have a closed path consisting of multiple Bezier curves and straight line segments. How can I tell whether the current position of my mouse pointer is inside or outside the path?

Example of mouse leaving the area:
on mouse leave

Example of mouse entering the area:
on mouse enter


Solution

  • First you should check if the graphics library you're using already provides this hit-testing.

    If you have to code it yourself, then a completely precise answer would require solving quadratic or cubic equations (depending on the degree of your Bezier curves) to determine the intersection with these paths. There seems to be a paper on exactly this problem.

    However I think it would be much more sensible to build a linear approximation to your path (i.e. evaluate the path densely) and then use a standard point-in-polygon test. This can be accurate to whatever tolerance you choose (e.g. one pixel).