Make image drawn on canvas draggable with JavaScript - Javascript Canvas

Javascript examples for Canvas:Mouse

Description

Make image drawn on canvas draggable with JavaScript

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; }
canvas{border:1px solid red;}

      </style> 
      <script>
$(function(){/* w  ww .  ja va2s. c o m*/
    var img = new Image();
    img.onload = function(){
        ctx.drawImage(img, 0,0);
    };
    img.src = "https://www.java2s.com/style/demo/Google-Chrome.png";
    var canvas=document.getElementById("canvas");
    var ctx=canvas.getContext("2d");
    var canvasOffset=$("#canvas").offset();
    var offsetX=canvasOffset.left;
    var offsetY=canvasOffset.top;
    var canvasWidth=canvas.width;
    var canvasHeight=canvas.height;
    var isDragging=false;
    function handleMouseDown(e){
      canMouseX=parseInt(e.clientX-offsetX);
      canMouseY=parseInt(e.clientY-offsetY);
      isDragging=true;
    }
    function handleMouseUp(e){
      canMouseX=parseInt(e.clientX-offsetX);
      canMouseY=parseInt(e.clientY-offsetY);
      isDragging=false;
    }
    function handleMouseOut(e){
      canMouseX=parseInt(e.clientX-offsetX);
      canMouseY=parseInt(e.clientY-offsetY);
    }
    function handleMouseMove(e){
      canMouseX=parseInt(e.clientX-offsetX);
      canMouseY=parseInt(e.clientY-offsetY);
      if(isDragging){
          ctx.clearRect(0,0,canvasWidth,canvasHeight);
          ctx.drawImage(img,canMouseX-128/2,canMouseY-120/2,128,120);
      }
    }
    $("#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="400" height="300"></canvas>  
   </body>
</html>

Related Tutorials