Canvas mouse events - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

Canvas mouse events

Demo Code

ResultView the demo in separate window

<!doctype html>
<html>
   <head> 
      <!-- reset css --> 
      <script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script> 
      <style>

#canvas{border:1px solid red;}

      </style> 
      <script>
$(function(){/*from w ww.j a  v  a  2 s.  c  o  m*/
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var $canvas=$("#canvas");
    var canvasOffset=$canvas.offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var rect1 = { x:30, y:30, width:50, height:25, color:"blue" };
    ctx.fillStyle=rect1.color;
    ctx.fillRect(rect1.x,rect1.y,rect1.width,rect1.height);
    function handleMouseMove(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      if(
          mouseX>=rect1.x &&
          mouseX<=rect1.x+rect1.width &&
          mouseY>=rect1.y &&
          mouseY<=rect1.y+rect1.height
          ){
              ctx.fillStyle="red";
              ctx.fillRect(rect1.x,rect1.y,rect1.width,rect1.height);
          }else{
              ctx.fillStyle=rect1.color;
              ctx.fillRect(rect1.x,rect1.y,rect1.width,rect1.height);
          }
    }
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
});

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

Related Tutorials