1

Say we drawed multiple rectangles in a html5 canvas:

    context.fillStyle='black';
    context.fillStroke='black';
    context.beginPath();
for(var i=0; i<50; i++)
{  
    context.rect(i*20,i*20,w,h);
//this is just some random configuration for the rectangles, it doesn't really matter how they are positioned
}
    context.closePath();
    context.fill();
    context.stroke();

How can I make it so it's recognizable when the user click on an individual rectangle and then, say, change it's color?

Is it possible or will I have to make a function that takes the mouse x and y coordinates and then check where it landed compared to the x and y coordinates of the rectangles, to finally find the one that "covers" the mouse coordinates?

badso
  • 109
  • 1
  • 11
  • 1
    Take a look at the hit test in this (possibly duplicate) stackoverflow post: http://stackoverflow.com/questions/15176968/how-to-change-mouse-over-to-onclick/15179322#15179322 – markE Oct 15 '15 at 02:24

1 Answers1

1

IMO it would be better to keep track of the rectangles inside an array and just loop through them to see if it's inside.

As stated Here:

When you draw to a canvas element, you are simply drawing a bitmap in immediate mode.

The elements (shapes, lines, images) that are drawn have no representation besides the pixels they use and their colour.[...]

Here comes the BUT: I found this Alternative

Community
  • 1
  • 1
FirstOne
  • 6,033
  • 7
  • 26
  • 45
  • Thanks, didn't think of recognizing the click that way. But I guess the other way, by taking the click coordinates is more efficient, since it will make operations only if the user clicks, differently to listening for clicks constantly. – badso Oct 15 '15 at 03:15
  • Also, if you are going to use the list of rectangles, make sure you check for the correct one if they have some parts covered by another ;D. @Vic – FirstOne Oct 15 '15 at 03:36