Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I would save a model of all the rectangles you want to draw with their coordinates. Then, you just have to listen to the mouseclick event (or mouseover event, whatever your needs) and browse through each element of your model to see if the mouse click was done inside the coordinates of a rectangle.</p> <p>As the previous posters said, you have to redraw your canvas every time you want to make a change to it (although you can speed things up by redrawing only the region of interest). Hope that helps a bit!</p> <p>EDIT:</p> <p>you could have a rectangle object defined:</p> <pre><code>function Rectangle(x, y, w, h) { this.x = x; this.y = y; this.w = w; this.h = h; this.contains = function(x, y) { return (x &gt; this.x &amp;&amp; x &lt;= (this.x + this.w) &amp;&amp; y &gt; this.y &amp;&amp; y &lt;= (this.y + this.h)); } this.clone = function() { return new Dimension(this.x, this.y, this.w, this.h); } } </code></pre> <p>and then have an array that would be your model : </p> <pre><code>var model = []; </code></pre> <p>And then add your rectangles to it:</p> <pre><code>model.push(new Rectangle(10,10,10,10));//x, y, width, height </code></pre> <p>Then, when you click on your canvas, you retrieve the mouse click coordinates from the mouse event and you loop over your array to see if the click was done inside one of the rectangles:</p> <pre><code>for (i = 0 ; i &lt; model.length ; i++) { if (model[i].contains(mouseEvent.x, mouseEvent.y)) //do something like redraw your canvas } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload