Interacting with Canvas Rectangle - Javascript Canvas

Javascript examples for Canvas:Rectangle

Description

Interacting with Canvas Rectangle

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-1.6.js"></script> 
      <script type="text/javascript">
    $(window).load(function(){// ww w  .j a va  2s .  c  o  m
var ctx = $('#cv').get(0).getContext('2d');
var rects = [[0, 0, 100, 100], [0, 150, 50, 100]];
for(var i=0;i<rects.length;i++) {
    ctx.fillRect(rects[i][0],
                 rects[i][1],
                 rects[i][2],
                 rects[i][3]);
}
$('#cv').click(function(e) {
    var x = e.offsetX,
        y = e.offsetY;
    for(var i=0;i<rects.length;i++) {
        if(x > rects[i][0]
        && x < rects[i][0] + rects[i][2]
        && y > rects[i][1]
        && y < rects[i][1] + rects[i][3]) {
            console.log('Rectangle ' + i + ' clicked');
        }
    }
});
    });

      </script> 
   </head> 
   <body> 
      <canvas width="400" height="400" id="cv"></canvas>  
   </body>
</html>

Related Tutorials