drawing a rectangle without clearing the canvas? - Javascript Canvas

Javascript examples for Canvas:Rectangle

Description

drawing a rectangle without clearing the canvas?

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>

body{ background-color: ivory; }
#wrapper{/*from w  w  w .j  a  v a  2 s  . c  om*/
   position:relative;
   width:300px;
   height:200px;
}
#canvas{
   position:absolute; top:0px; left:0px;
   border:1px solid green;
   width:100%;
   height:100%;
}
#canvas2{
   position:absolute; top:0px; left:0px;
   border:3px solid red;
   width:100%;
   height:100%;
}

      </style> 
      <script>
$(function(){
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var canvas2=document.getElementById("canvas2");
    var ctx2=canvas2.getContext("2d");
    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var startX;
    var startY;
    var isDown=false;
    $("#canvas2").css({ left:-500, top:0 });
    function drawRect(toX,toY,context){
        context.beginPath();
        context.rect(startX,startY,toX-startX,toY-startY);
        context.stroke();
    }
    function handleMouseDown(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      startX=mouseX;
      startY=mouseY;
      ctx2.clearRect(0,0,canvas2.width,canvas2.height);
      $("#canvas2").css({ left:0, top:0 });
      isDown=true;
    }
    function handleMouseUp(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      // Put your mouseup stuff here
      isDown=false;
      $("#canvas2").css({ left:-500, top:0 });
      drawRect(mouseX,mouseY,ctx);
    }
    function handleMouseOut(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      // Put your mouseup stuff here
      isDown=false;
      $("#canvas2").css({ left:-500, top:0 });
      drawRect(mouseX,mouseY,ctx);
    }
    function handleMouseMove(e){
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      // Put your mousemove stuff here
      ctx2.clearRect(0,0,canvas2.width,canvas2.height);
      drawRect(mouseX,mouseY,ctx2);
    }
    $("#canvas").mousedown(function(e){handleMouseDown(e);});
    $("#canvas").mousemove(function(e){handleMouseMove(e);});
    $("#canvas").mouseup(function(e){handleMouseUp(e);});
    $("#canvas").mouseout(function(e){handleMouseOut(e);});
}); // end $(function(){});

      </script> 
   </head> 
   <body> 
      <p>Drag to draw a rect</p> 
      <div id="wrapper"> 
         <canvas id="canvas2" width="300" height="200"></canvas> 
         <canvas id="canvas" width="300" height="200"></canvas> 
      </div>  
   </body>
</html>

Related Tutorials