views:

52

answers:

2

Hi All,

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?

+1  A: 

Roughly, you can do it like this:

var click_x = event.layerX;
var click_y = event.layerY;

for ( var i = 0; i < rects.length; i++ ) {
    var rect = rects[i];
    if ( click_x >= rect.x && click_x <= rect.x + rect.width
    &&   click_y >= rect.y && click_y <= rect.y + rect.height ) {
        // The click was inside the rectange
    }
}

Assuming we're dealing with non-negative widths and heights :)

tomit
Is there no better way other than looping through every rectangle and checking the dimensions... (Sigh!!)
pǝlɐɥʞ
You could use something like a [bounding volume hierarchy (BVH)](http://en.wikipedia.org/wiki/Bounding_volume_hierarchy) to split up the space and narrow down the rectangles that need to be checked. This will requires some preprocessing though.
tomit
+1  A: 

This may be overkill, but Cake JS will do the job for rectangles and other shapes. Check out the demo.

brainjam
He's got a whole event handling subsystem, you are right, it is a bit of an overkill for my needs.
pǝlɐɥʞ