May be some one has had similar experiences on this dilemma and can help me out here…
Basically, I have a canvas element on which I draw several rectangles in a loop using
context.fillRect (x, y, width, height)
Now, I want some of the rectangles to be hotspots and respond to click events. I can find out the exact (x,y) of a click event using event.layerX and event.layerY.
Given that I know the following:
- the exact x,y of the click
- the x,y,width and height of every rectangle
how do I find out if the click event occurred inside the perimeter a certain rectangle or not?
and,
which rectangle the click event occurred 0n?
Is there like a mathematical formula for this?
Any help would be much appreciated, and if I’m not clear enough, let me know…
Thanks
EDIT
Is there no better way than to loop through all rectangles and check their position and dimensions?
This is a general topology problem frequently encountered when using maps.
The algorithm for deciding whether a point is within ANY polygon (rectangles, circles, irregular shapes) is as follows:
From the point being checked construct any line in any direction until the edge of the screen area in which your polygons are located
if the line intersects any polygon boundary at an odd number of places then it is within that polygon
if the line intersects any polygon boundary an even number of places it is outside that polygon.
Notes:
The direction of the line is irrelevant
Will not work if a polygon is cut at the side of the screen without closure
If the polygon cuts over itself then the algorithm can fail if the line
happens to pass through the cutpoint (eg in the figure 8 considered as a
single polygon where the line passes exactly through where upper and lower
parts connect of the figure connect)