Drawing with canvas - Javascript Canvas

Javascript examples for Canvas:Draw

Description

Drawing with 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-1.7.1.js"></script> 
      <script type="text/javascript">
    $(window).load(function(){/*from   ww  w .j  av  a  2s .  c o  m*/
$(function() {
    var letsdraw = false;
    var theCanvas = document.getElementById('paint');
    var ctx = theCanvas.getContext('2d');
    theCanvas.width = 420;
    theCanvas.height = 300;
    var canvasOffset = $('#paint').offset();
    $('#paint').mousemove(function(e) {
        if (letsdraw === true) {
            ctx.lineTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
            ctx.stroke();
        }
    });
    $('#paint').mousedown(function() {
        letsdraw = true;
        ctx.strokeStyle = 'blue';
        ctx.lineWidth = 10;
        ctx.lineCap = 'round';
        ctx.beginPath();
        ctx.moveTo(e.pageX - canvasOffset.left, e.pageY - canvasOffset.top);
    });
    $(window).mouseup(function() {
        letsdraw = false;
    });
});
    });

      </script> 
   </head> 
   <body> 
      <canvas id="paint" style="border:solid; margin-top: 50px;"></canvas>  
   </body>
</html>

Related Tutorials