Mouse drag and draw - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

Mouse drag and draw

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  ava2 s  .c  o  m
    var canvas=document.getElementById("surface");
    var context=canvas.getContext("2d");
    var canvasOffset=$("#surface").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    context.strokeStyle = "#df4b26";
    context.lineJoin = "round";
    context.lineWidth = 5;
    var clickX = new Array();
    var clickY = new Array();
    var clickDrag = new Array();
    var paint;
    var context;
        $('#surface').mousedown(function(e){
            var touchX = e.clientX - offsetX;
            var touchY = e.clientY - offsetY;
            paint = true;
            clickX.push(e.clientX-offsetX);
            clickY.push(e.clientY-offsetY);
            lastX=touchX;
            lastY=touchY;
        });
        $('#surface').mousemove(function(e){
            if(paint){
                var x=e.clientX-offsetX;
                var y=e.clientY-offsetY;
                clickX.push(x);
                clickY.push(y);
                context.beginPath();
                context.moveTo(lastX,lastY)
                context.lineTo(x,y);
                context.stroke();
                context.closePath();
                lastX=x;
                lastY=y;
            }
        });
        $('#surface').mouseup(function(e){
            paint = false;
        });
        $('#surface').mouseleave(function(e){
            paint = false;
        });
}); // end $(function(){});

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

Related Tutorials