drag and draw - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

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>

#wrapper{/*from   w  w w  .  ja  v  a2s  .  co  m*/
   position:relative;
   width:300px;
   height:200px;
}
#canvas,#canvasTemp{
   position:absolute; top:0px; left:0px;
   border:1px solid blue;
   width:100%;
   height:100%;
}
#canvasTemp{ border:1.5px solid green; }
#canvas{ border:1px solid red; }

      </style> 
      <script>
$(function(){
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var canvasTemp=document.getElementById("canvasTemp");
    var ctxTemp=canvasTemp.getContext("2d");
    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var startX;
    var startY;
    var isDown=false;
    $("#canvasTemp").css({ left:-500, top:0 });
    function drawLine(toX,toY,context){
        context.beginPath();
        context.moveTo(startX, startY);
        context.lineTo(toX,toY);
        context.stroke();
    }
    function handleMouseDown(e){
      e.preventDefault();
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      startX=mouseX;
      startY=mouseY;
      ctxTemp.clearRect(0,0,canvasTemp.width,canvasTemp.height);
      $("#canvasTemp").css({ left:0, top:0 });
      isDown=true;
    }
    function handleMouseUp(e){
      e.preventDefault();
      if(!isDown){return;}
      isDown=false;
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      $("#canvasTemp").css({ left:-500, top:0 });
      drawLine(mouseX,mouseY,ctx);
    }
    function handleMouseMove(e){
      e.preventDefault();
      if(!isDown){return;}
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      ctxTemp.clearRect(0,0,canvasTemp.width,canvasTemp.height);
      drawLine(mouseX,mouseY,ctxTemp);
    }
    $("#canvas").mousedown(function(e){handleMouseDown(e);});
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
    $("#canvas").mouseup(function(e){handleMouseUp(e);});
    $("#canvas").mouseout(function(e){handleMouseUp(e);});
}); // end $(function(){});

      </script> 
   </head> 
   <body> 
      <div id="wrapper"> 
         <canvas id="canvasTemp" width="300" height="200"></canvas> 
         <canvas id="canvas" width="300" height="200"></canvas> 
      </div>  
   </body>
</html>

Related Tutorials