30

I was able to successfully draw an image on an HTML canvas. But I need to be able to drag the image about on the canvas.

I know this function can be implemented easily by some JavaScript libraries like KinectJS. But I want to just do it with simple JavaScript.

window.onload = function(){
var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var destX = 0;
var destY = 0;
var imageObj = new Image();

imageObj.onload = function(){
  context.drawImage(imageObj, destX, destY);
};
imageObj.src = "westeros.png";
<canvas id="myCanvas" height=1024 width=360></canvas>
dakab
  • 5,379
  • 9
  • 43
  • 67
Donnie Ibiyemi
  • 971
  • 3
  • 15
  • 26

2 Answers2

41

To do dragging you handle 3 mouse events:

  1. mousedown -- set a flag indicating that the drag has begun.

  2. mouseup -- clear that drag flag because the drag is over

  3. mousemove -- if the drag flag is set, clear the canvas and draw the image at the mouse position

Here is some code:

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>

<style>
    body{ background-color: ivory; }
    canvas{border:1px solid red;}
</style>

<script>
$(function(){


    var img = new Image();
    img.onload = function(){
        ctx.drawImage(img, 0,0);
    };
    img.src = "http://images.christmastimeclipart.com/images/2/1271716593176_1788/img_1271716593176_17881.jpg";

    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);
      // set the drag flag
      isDragging=true;
    }

    function handleMouseUp(e){
      canMouseX=parseInt(e.clientX-offsetX);
      canMouseY=parseInt(e.clientY-offsetY);
      // clear the drag flag
      isDragging=false;
    }

    function handleMouseOut(e){
      canMouseX=parseInt(e.clientX-offsetX);
      canMouseY=parseInt(e.clientY-offsetY);
      // user has left the canvas, so clear the drag flag
      //isDragging=false;
    }

    function handleMouseMove(e){
      canMouseX=parseInt(e.clientX-offsetX);
      canMouseY=parseInt(e.clientY-offsetY);
      // if the drag flag is set, clear the canvas and draw the image
      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>
markE
  • 102,905
  • 11
  • 164
  • 176
  • 1
    Easy to add touch. For touch, you would handle these 3 events similar to mouse events: touchstart, touchend & touchmove. – markE Feb 23 '13 at 06:09
  • Touch is a broad topic to summarize and can vary by o/s, but generally: (1) listen for “touchmove” then (2) grab the position via touches[0].pageX & .pageY and (3) drawImage at the x/y. You must event.preventDefault() to stop touchevents dragging the page. [canvas.addEventListener("touchmove", handleMove, false); function handleMove(e) { e.preventDefault(); var touches = e.originalEvent.touches; if(isDragging){ ctx.clearRect(0,0,canvasWidth,canvasHeight); ctx.drawImage(img,touches[0].pageX-128/2,touches[0].pageY-120/2,128,120);}}] – markE Feb 23 '13 at 07:52
  • How can one make it draggable *outside* of the canvas? – Jaigus Jan 10 '14 at 22:22
  • 2
    Don't confuse a canvas drawing with a DOM element. Canvas drawings are only pixels on the canvas surface. Therefore, they are limited to displaying inside the canvas and cannot be dragged outside of the canvas. – markE Jan 10 '14 at 22:42
  • Thanks @markE. Your solution is working for me. I wanted to know, is it possible to add multiple draggable images inside single canvas?. I have tried doing the same, but ctx.clearRect is resetting my whole canvas. Please suggest if any alternative. – Sid Mar 18 '16 at 19:34
  • 1
    @Sid Here's a [previous Q&A](http://stackoverflow.com/questions/27471968/cant-make-image-draggable-on-canvas/27475160#27475160) with an example showing how to drag multiple images. Cheers! – markE Mar 18 '16 at 20:29
5

markE's answer got me most of the way there, but I had some problems with it recognizing the location my mouse was in. I'm attaching my code although since I work with OO JS it'll be differently structured:

    hitImage: function() {
      return (this.startX > this.imageX && 
              this.startX < this.imageX + this.imageWidth && 
              this.startY > this.imageY && 
              this.startY < this.imageY + this.imageHeight);
    },
    
    handleMouseDown: function(e){
      this.startX = parseInt(e.clientX - this.offsetX);
      this.startY = parseInt(e.clientY - this.offsetY);
      // set the drag flag
      this.isDragging= this.hitImage;
    },

    handleMouseUp: function(e,img){
      this.startX=parseInt(e.clientX-this.offsetX);
      this.startY=parseInt(e.clientY-this.offsetY);
      // clear the drag flag
      this.isDragging=false;
      this.drawImage(e,img);
    },

    handleMouseOut: function(e,img){
      this.handleMouseUp(e,img);
    },

    handleMouseMove: function(e,img){
      // only compute new positions if in drag
      if(this.isDragging){
        this.canMouseX=parseInt(e.clientX - this.offsetX);
        this.canMouseY=parseInt(e.clientY - this.offsetY);
        // move the image by the amount of the latest drag
        var dx = this.canMouseX - this.startX;
        var dy = this.canMouseY - this.startY;
        this.imageX += dx;
        this.imageY += dy;
        // Negative image locations break the pattern in this.fillPattern
        this.imageY = Math.max(0, this.imageY);
        this.imageX = Math.max(0, this.imageX);

        // reset the startXY for next time
        this.startX = this.canMouseX;
        this.startY = this.canMouseY;
        this.drawImage(e,img);
      }
Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
cpres
  • 953
  • 1
  • 10
  • 13
  • I am learning to drag image with HTML5 canvas. I am interested with your approach, but I found a problem: I can't find the drawImage() function anywhere in your code. Could you please provide a plunker or fiddle for this snippet? Thank you. – asubanovsky Jan 21 '16 at 10:50
  • You can learn about the drawImage function here: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/drawImage – cpres Jan 29 '16 at 21:58