HTML5 Drag and Drop Mobile Tutorial

Learn to add drag and drop for games and mobile site development, with HTML5.

Mobile Drag and Drop Example Introduction Initialization Resize the Canvas Draw the Image Tips Summary Source Code Page


This article explains how to drag and drop an image with HTML5. The Mobile Drag and Drop Example works with HTML5 compatible mobile devices.

The tutorial includes how to resize the canvas when the device reorients, snap to drop regions on the canvas, center the graphic under the touch point, draw the graphic after loading, helpful tips, and how to include desktop drag and drop.


When the Web page loads the Mobile Drag and Drop Example calls function loadGame(). Function loadGame() obtains a reference to the canvas and 2D context. loadGame() sets the lineWidth for drawing the border, then calls functions to load the graphic, and resize the canvas.

Function loadGame() assigns the touchmove event listener to the canvas. The touchmove event listener only captures touch movement on mobile devices. The desktop onmousemove event listener is assigned with HTML. The entire loadGame() function follows.

function loadGame(){
try {
cvs = document.getElementById(

context = cvs.getContext(

context.lineWidth = 4;

 function (e) 

 if (e.targetTouches.length > =  1) 

  var t1 = e.targetTouches[0];

   t1.pageX- iOffsetX,
   t1.pageY- iOffsetY

catch (err){



Load the Graphic

The initialization function loadGame() calls function loadGraphic(). Function loadGraphic() initializes an Image for use during drag and drop operations.

First create an Image reference.

im = new Image();

Second assign the path to an image file to the src property.

im.src = "assets/digit7.gif";

Third assign an onload event listener for the Image. Wait for the source image to load before drawing the graphic to the canvas.

im.onload = function() { 

See the loadGraphic() function's full source code.

Resize the Canvas

When a mobile device is reoriented, a desktop web browser size changes, or the user zooms, then the onresize event handler is called. The following HTML markup assigns resizeCanvas() as the onresize event handler for the Web page.



Compute as much as possible when the window resizes, and compute as little as possible when drawing the graphic. Most likely the browser window will resize much less often than the graphic will redraw. Therefore resizeCanvas() executes much less often than code which displays the graphic. Function resizeCanvas() prepares as much data as possible for use during drawing operations. The graphic's redrawn many times when the user drags across the canvas. Keep operations to a minimum while the graphic is moving.

resizeCanvas() sets the size of the canvas to 90% of the width and height of the current window. That allows the user to drag the image around the canvas without scrolling.

Additionally resizeCanvas() calculates the dimensions of the image we're dragging, position offsets for snapping, touch point center offsets, and the top left coordinates of the square box at the bottom of the example. The image is square. Image dimensions are saved to variable iDim.

Position offsets for snapping are saved to variables iSnapTX,iSnapTY,iSnapBX, and iSnapBY. The variable names represent top T and bottom B, X and Y coordinates. Offsets to center the image under the touch point are saved to iOffsetX,iOffsetY.

Drop Boxes

On mobile devices the image snaps to boxes in the upper left and bottom right of the canvas. The width and height of each box equals the width and height of the image. The upper left box's upper left corner coordinates equal (0,0). Both X and Y coordinates are zero for the top left box. The bottom right box's upper left coordinates vary depending on the browser's available width and height. The top left coordinates for the bottom right box are saved to variables iBx,iBy. The following screen shot of the Mobile Drag and Drop Example shows the top left and bottom right snap boxes outlined in blue. The drag image is a number seven.

Drag Drop Mobile Example Screen Shot

Mobile Drag and Drop Screen Shot

Last resizeCanvas() draws the image in the upper left hand snap box, and then calls redrawBorders(). Whenever the canvas resizes the image redraws in the default upper left hand drop box. Function redrawBorders() draws the blue borders around the drop boxes.

See the resizeCanvas() function's full source code.

Draw Borders

The redrawBorders() function draws the borders around the two drop boxes. Function redrawBorders() executes often. Therefore we don't want to perform extra calculations in redrawBorders(). The following listing includes the entire redrawBorders() function.

function redrawBorders(){	


// Top rectangle:

// Bottom rectangle:

Draw the Image

JavaScript API method drawGraphic() fills the entire canvas with black, draws the graphic based on the user's current touch point, then calls redrawBorders().

drawGraphic() is called by both the mobile touchmove event listener and the desktop onmousemove event listener. Function drawGraphic() determines if the current touch point is within snapping distance of the top or bottom blue box. If so drawGraphic() draws the image inside the appropriate box.

If the graphic is moving between boxes, then drawGraphic() draws the image underneath the user's touch point.

See the drawGraphic() function's full source code.

Tips, Tricks, and Issues

Try/Catch Blocks

The HTML5 Drag and Drop Mobile Source Code wraps loadGame() statements with a try/catch block. The try/catch block traps errors and displays them to the user. The try/catch block displays error messages generated within loadGame() and any functions loadGame() calls.

Try/catch blocks are great for development. They help programmers see unexpected errors. A try/catch block in a function at the top of the call stack catches any uncaught errors down the stack. Sometime's it's helpful to include a try/catch block in a top level function, in order to catch errors from functions down the stack.

However try/catch blocks can slow down performance. Performance critical functions should not include try/catch blocks when released to the public.

HTML5 Drag and Drop Mobile Source Code doesn't include try/catch blocks within high performance functions such as redrawBorders(), mouseMoveCanvas(), drawGraphic(), or the anonymous touchmove event listener.

Use try/catch blocks where they'll provide the most help during development. Remove try/catch blocks for Web content before release.

Drag and Drop for Mobile

Drag and drop for desktops and non mobile devices is relatively straightforward. Please see the HTML5 Drag and Drop Example for more information. For desktop computers it's easy to assign ondragstart,ondragover, and ondrop event listeners. However mobile devices have a few more limitations.

Drag and drop on a mobile device requires either preventing the page from scrolling, capturing scroll events, or drawing the canvas from the top of the browser window. This example places the canvas at the top of the browser window. See the Drag a Sprite example which includes a set of tutorials to implement mobile interaction, wherever you choose to place the canvas.


With this example, if the user zooms into the view using a mobile device, then resizeCanvas() sets dimensions based on the canvas itself, rather than the view screen. Essentially some of the canvas may remain offscreen, after a zoom operation. However the graphic still responded to touch events, when we tested.


This article explained how to drag and drop an image with HTML5. The Mobile Drag and Drop Example works with HTML5 compatible mobile devices.

The tutorial included how to resize the canvas when the device reorients, snap to drop regions on the canvas, center the graphic under the touch point, draw the graphic after loading, helpful tips, and how to include desktop drag and drop. See the HTML5 Drag and Drop Mobile Source Code for details. See More Drag & Drop Examples.

Have fun and love learning!

More Drag & Drop Examples

Ad for 3D Marketing Learn 3D Programming Ad
Copyright © 2015 Seven Thunder Software. All Rights Reserved.