Mobile Interactive Sprite Tutorial

Learn to add sprites which move in response to touch, for mobile games.

Mobile Interactive Sprite Example Introduction Draw the Sprite Respond to Resize Events Tips Summary HTML Markup JavaScript CSS Source Code Page

Introduction

Learn mobile site development for games and other Web projects. This tutorial explains how to implement interactive sprites with HTML5. Topics include how to use the touchmove event for mobile devices and onmousemove event for desktop computers.

This article covers code which responds when the mobile device is reoriented or the browser window is resized. The sprite responds to simple edge detection as well. Edge detection provides the impression of boundaries around the sprite. The sprite doesn't overlap or partially disappear when it's near the edge of the canvas.

Sprite Interaction Basics

Implementing interactive sprites for mobile devices is fairly straight forward. Create a canvas, an Image, draw the image onto the canvas, and assign a touchmove event handler for the canvas. Detect when the device is reoriented, obtain the new dimensions, then redraw everything.

Initialization

When the page first loads, obtain a reference to the canvas, and the canvas's 2D context. Create an image. The following listing obtains the 2D context, obtains a reference to the content area of the Web page, and creates an Image reference. Later we'll show how to draw the image after it loads.

context = cvs.getContext(
 '2d'
);

content = document.getElementById(
 'content'
);

img = new Image();		
		

Assign a touchmove event to the canvas. The following listing demonstrates assigning a touchmove event handler with an anonymous function which calls our drawGraphic() function.

cvs.addEventListener(

'touchmove', 

 function (e) 
 {

 e.preventDefault();	
		
 if (e.targetTouches.length >=  1) 
 {
  var t1 = e.targetTouches[0];
  drawGraphic(
   t1.pageX,
   t1.pageY
  );
 }
 },
 false
);		
		

Draw the Sprite

This section explains how to implement a method to draw the sprite onto the canvas and respond to the edges of the canvas. Edge detection prevents the sprite from partially disappearing as it attempts to cross beyond the edge of the canvas.

First clear the previous frame. Otherwise all previous sprite movement displays at the same time.

Second be sure the bounding box of the canvas has been initialized. The bounding box variable in our example is named bb.

Third provide edge detection.

Code initializes two variables named I_DIM and I_HALF_DIM. The variables represent the dimension of the square sprite and half the dimension of the square sprite, respectively.

A set of if-else statements check to see if the sprite has crossed the right, left, top, and bottom boundaries. If not, offset the sprite such that it appears as if the mouse cursor or touch point is centered on the sprite. Normal drawing places the touch point at the top left corner. Centering places the touch point in the center of the sprite.

The following listing includes the entire drawGraphic() function.

Function drawGraphic()

function drawGraphic(
 iX,
 iY
)
{
if (bb != null){		
context.clearRect(
 0,
 0,
 bb.width,
 bb.height
);
	
// Offset ball so it won't 
//display right of the right side.
if (iX + I_HALF  > bb.width){
iX -= I_DIM;			
}

// Offset the ball, so the pointer
// displays in the ball's horizontal center.	
else if (iX  > I_DIM) {
 iX -= I_HALF;
}	

// Offset ball so it won't 
//display below the bottom.
if (iY + I_HALF  > bb.height){
 iY -= I_DIM;			
}
	
// Place the ball in the 
// vertical center of the pointer.
else if (iY  > I_DIM) {
 iY -= I_HALF;
}	
// Place element where one finger touched:						
if (img != null && context != null){
 context.drawImage(
  img,
  iX,
  iY,
  I_DIM,
  I_DIM
 );

 }
 else {
  alert
  (
    "Problem with data: "+img+" context:"+context
   );
  }
 }
}	
		
		

Respond to Resize Events

Desktops trigger resize events when the user changes the dimensions of their browser window. Mobile devices activate resize events when the user resizes the view or rotates the device between portrait and landscape orientation.

The following listing of resizeCanvas() responds to events which resize the canvas. Function resizeCanvas() first assigns width and height to the canvas element based on the window's width and height. Last resizeCanvas() draws the sprite with a call to JavaScript API method drawImage(). Other tutorials at SevenThunderSoftware.com discuss drawImage() in detail. For example see the Beginner's Guide to Sprite Sheets Tutorial.

function resizeCanvas(){

var iW = Number(
 window.innerWidth
);

var iH = Number(
 window.innerHeight
);

if (context != null && img != null){

context.canvas.width = iW;

context.canvas.height = iH;

bb = cvs.getBoundingClientRect();

if (bInit == true){

// To trigger display 
// with new dimensions. 
img.src = "circle.gif"; 
	
img.onload = function() {
					
context.drawImage(
 img,
 0,
 0,
 I_DIM,
 I_DIM,
 cvs.width/2,
 cvs.height/2, 
 I_DIM,
 I_DIM
);
};

 //Let future code know we've 
 // already loaded the sprite.
 bInit = false; 		
}
else {

context.drawImage(
 img,
 0,
 0,
 I_DIM,
 I_DIM,
 cvs.width/2,
 cvs.height/2, 
 I_DIM,
 I_DIM
);
}
}
}		
		

Tips, Tricks, and Issues

Assign two event listeners to detect movement. Assign both the touchmove event listener for mobile devices, and the onmousemove event listener for desktops. Both event handlers eventually call our drawGraphic() function. Function drawGraphic() was listed previously.

The desktop onmousemove event handler also translates from browser coordinates to canvas coordinates with function translateToCanvasCoords(). The mobile touchmove event doesn't need translation for this Mobile Interactive Sprite example.

Redraw the Image

When initializing an image, draw the image after it loads.The following listing demonstrates drawing the image with the JavaScript 2D canvas API method drawImage(), after the image loads. In the following listing drawImage() is activated in response to the image's onload event listener.

img.onload = function() {					
context.drawImage(
 img,
 0,
 0,
 I_DIM,
 I_DIM,
 cvs.width/2,
 cvs.height/2, 
 I_DIM,
 I_DIM
);
};		


// Let other functions know we've 
// already loaded the sprite. 
bInit = false; 	
}
		

When the browser is resized or the device reoriented, redraw the image programmatically. The following listing demonstrates redrawing when bInit equals false. Variable bInit equals false after the image has loaded. Attempting to draw an image before download and loading creates an exception error.

if (bInit == false){
context.drawImage(
 img,
 0,
 0,
 I_DIM,
 I_DIM,
 cvs.width/2,
 cvs.height/2, 
 I_DIM,
 I_DIM
);
}		
		

Summary

This tutorial explained how to implement interactive sprites with HTML5. Topics include how to use the touchmove event for mobile devices and onmousemove event for desktop computers.

This article covered code which responds when the mobile device is reoriented or the browser window is resized. The sprite responds to simple edge detection as well. Edge detection provides the impression of boundaries around the sprite. The sprite doesn't overlap or partially disappear when it's near the edge of the canvas.

See the Mobile Interactive Sprite Source Code. See more HTML5 examples below.

Have fun and love learning!

Sprite Sheet Animation
Copyright © 2015 Seven Thunder Software. All Rights Reserved.