Draw on canvas: mouse over and mouse click - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

Draw on canvas: mouse over and mouse click

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

#canvas{/*from  w ww .j a  v  a 2  s  . c o m*/
   border: 1px solid black;
}
#clear:hover{
   cursor: pointer;
   text-decoration: underline;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var enableDraw = false;
$("#canvas").mousedown(function(arg) {
    enableDraw = true;
});
$("#canvas").mouseup(function(arg) {
    enableDraw = false;
});
$("#canvas").mousemove(function(arg) {
    if(enableDraw){
        context.fillStyle = "#1477CC";
        var pos = getMousePos(canvas, arg);
        context.beginPath();
        context.arc(pos.x+50,pos.y,5,0,2*Math.PI);
        context.fill();
    }
});
function getMousePos(canvas, e) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
    };
}
//Clear
$("#clear").click(function() {
    var c = document.getElementById("canvas");
   var ctx = c.getContext("2d");
   ctx.fillStyle = "#FFFFFF";
   ctx.fillRect(0,0,380,300);
});
    });

      </script> 
   </head> 
   <body> 
      <canvas id="canvas"> 
      </canvas> 
      <div onclick="clear();" id="clear">
          Clear 
      </div>  
   </body>
</html>

Related Tutorials