perform mouse action on HTML canvas? - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

perform mouse action on HTML canvas?

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-2.1.4.js"></script> 
      <style id="compiled-css" type="text/css">

html, body {
   width: 100%;
   height: 100%;
   margin: 0;
   padding: 0;
}


      </style> 
      <script type="text/javascript">
    window.onload=function(){//from   w w w  .j  a v a2  s . c o m
var canvas = document.getElementById('myCanvas'),
   context = canvas.getContext('2d'),
   circles = [];
var Circle = function(x, y, radius) {
      this.x = x;
    this.y = y;
    this.left = x - radius;
    this.top = y - radius;
    this.right = x + radius;
    this.bottom = y + radius;
    this.radius = radius;
};
Circle.prototype.draw = function(context) {
      context.beginPath();
    // create the circle using the arc
    context.arc(this.x, this.y, this.radius, 0, 2 * Math.PI, false);
    //set the fill color to a random color
    context.fillStyle = '#'+Math.floor(Math.random()*16777215).toString(16);
    //fill the circle
    context.fill();
    //set the text color to white
    context.fillStyle = '#FFF';

    context.textAlign = "center";

    context.font = 'Helvetica';

    context.fillText(circles.length+1, this.x, this.y);
}
var drawCircle = function (context, x, y, radius) {

    var circle = new Circle(x, y, radius);

    circle.draw(context);

    circles.push(circle);
};

for(var i=0; i < 5; i++) {
   var x = Math.floor(Math.random() * 500) + 1,
     y = Math.floor(Math.random() * 500) + 1 ;
    drawCircle(context, x, y, 20);
}

$('#myCanvas').click(function (e) {
    var mouseX = e.pageX - this.offsetLeft,
          mouseY = e.pageY - this.offsetTop;
    for (var i = 0; i < circles.length; i++) {
        if (mouseX < circles[i].right && mouseX > circles[i].left && mouseY > circles[i].top && mouseY < circles[i].bottom) {
            console.log('clicked circle ' + (i + 1));
        }
    }
});
    }

      </script> 
   </head> 
   <body> 
      <canvas id="myCanvas" width="500px" height="500px"></canvas>  
   </body>
</html>

Related Tutorials