drag image after dropping it in canvas element - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

drag image after dropping it in canvas element

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(){//  ww w  . j  a va 2 s. c o  m
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var isDown=false;
    var startX;
    var startY;
    var imgX=50;
    var imgY=50;
    var imgWidth,imgHeight;
    var img=new Image();img.onload=start;img.src="https://www.java2s.com/style/demo/InternetExplorer.png";
    function start(){
        imgWidth=img.width;
        imgHeight=img.height;
        ctx.drawImage(img,imgX,imgY);
    }
    function handleMouseDown(e){
      e.preventDefault();
      startX=parseInt(e.clientX-offsetX);
      startY=parseInt(e.clientY-offsetY);

      if(startX>=imgX && startX<=imgX+imgWidth && startY>=imgY && startY<=imgY+imgHeight){
          isDown=true;
      }
    }
    function handleMouseUp(e){
      e.preventDefault();
      isDown=false;
    }
    function handleMouseOut(e){
      e.preventDefault();
      isDown=false;
    }
    function handleMouseMove(e){
      if(!isDown){return;}
      e.preventDefault();
      mouseX=parseInt(e.clientX-offsetX);
      mouseY=parseInt(e.clientY-offsetY);
      // Put your mousemove stuff here
      if(!isDown){return;}
      imgX+=mouseX-startX;
      imgY+=mouseY-startY;
      startX=mouseX;
      startY=mouseY;
      ctx.clearRect(0,0,canvas.width,canvas.height);
      ctx.drawImage(img,imgX,imgY);
    }
    $("#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> 
      <canvas id="canvas" width="300" height="300"></canvas>  
   </body>
</html>

Related Tutorials