Draw on HTML5 Canvas using a mouse - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

Draw on HTML5 Canvas using a mouse

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <title>Free drawing and erase on canvas with mouse</title> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.3.js"></script> 
      <style id="compiled-css" type="text/css">

canvas {/*w ww  .  j  a  v  a  2s  .co m*/
   cursor: crosshair;
   border: 1px solid #000000;
}


      </style> 
      <script type="text/javascript">
    $(window).load(function(){

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

var canvasx = $(canvas).offset().left;
var canvasy = $(canvas).offset().top;
var last_mousex = last_mousey = 0;
var mousex = mousey = 0;
var mousedown = false;
var tooltype = 'draw';
//Mousedown
$(canvas).on('mousedown', function(e) {
    last_mousex = mousex = parseInt(e.clientX-canvasx);
   last_mousey = mousey = parseInt(e.clientY-canvasy);
    mousedown = true;
});
//Mouseup
$(canvas).on('mouseup', function(e) {
    mousedown = false;
});
//Mousemove
$(canvas).on('mousemove', function(e) {
    mousex = parseInt(e.clientX-canvasx);
    mousey = parseInt(e.clientY-canvasy);
    if(mousedown) {
        ctx.beginPath();
        if(tooltype=='draw') {
            ctx.globalCompositeOperation = 'source-over';
            ctx.strokeStyle = 'black';
            ctx.lineWidth = 3;
        } else {
            ctx.globalCompositeOperation = 'destination-out';
            ctx.lineWidth = 10;
        }
        ctx.moveTo(last_mousex,last_mousey);
        ctx.lineTo(mousex,mousey);
        ctx.lineJoin = ctx.lineCap = 'round';
        ctx.stroke();
    }
    last_mousex = mousex;
    last_mousey = mousey;
    //Output
    $('#output').html('current: '+mousex+', '+mousey+'<br/>last: '+last_mousex+', '+last_mousey+'<br/>mousedown: '+mousedown);
});

use_tool = function(tool) {
    tooltype = tool; //update
}
    });

      </script> 
   </head> 
   <body> 
      <canvas id="canvas" width="800" height="500"></canvas> 
      <input type="button" value="draw" onclick="use_tool('draw');"> 
      <input type="button" value="erase" onclick="use_tool('erase');"> 
      <div id="output"></div>  
   </body>
</html>

Related Tutorials