Animated Effects

Graphical Explosion Effect Tutorial

Animate Explosions Over Background Graphics

Exploding Coffee Pot Example Introduction Display the Background Start the Timer Display the Sprite Sheet Stop the Explosion Tips Summary Create Explosion Graphics Tutorial Explosion Effect Graphic HTML Markup JavaScript CSS Source Code Page

Introduction

This tutorial teaches how to animate a graphical explosion over a background image. We explain how to code an interactive explosion effect with sprite sheets, HTML5, the canvas element, and JavaScript. For an introduction to sprite sheets see the Beginner's Guide to Sprite Sheets Tutorial. To design the graphics see the Create Explosion Graphics Tutorial.

Overview

This tutorial applies to both the Exploding Coffee Pot Example and the Explosion Over Text Example. Only the background graphic and Web page background colors change. Other than that, the code remains the same for both examples.

This tutorial covers three steps plus responsive Web design. First display a background graphic with just one frame. Second in response to a tap on the canvas, prepare a timer to draw sprites over the background graphic. Third display a sprite sheet with multiple frames for use as an explosion.

With optimized graphics and code there's no need to redraw the background graphic or clear the canvas between animation frames. Use sprite sheets with transparency such as a GIF or PNG files. To design the graphics see the Create Explosion Graphics Tutorial.

Fixed Widths Versus Responsive Design

This tutorial focuses on fixed dimensions for the canvas, background image, and sprites. JavaScript and CSS hard code dimensions for the background image, canvas, location of the explosion, and size of the explosion sprite. Fixed sizes display in the source code with upper case letters such as I_BG_DIM_X, and I_BG_DIM_Y, which represent the background image's X and Y dimensions. Fixed or unchanging sizes make the tutorial easier to understand yet more difficult for responsive Web design. Responsive design allows animation and graphics to work better with mobile devices. Fortunately the background and sprite images are small enough to apply responsive design. Usually images less than 300 pixels wide and tall display without resizing on mobile phones. Therefore hard coded sizes less than or equal to 300 pixels should work fine.

Responsive Design

Ideally use responsive design for dimensions and locations. The width and height of the canvas should change based on the orientation and screen size of the viewing device. Allow JavaScript to resize the canvas based on the device's browser display area, when the user rotates the device or resizes the browser window. After resizing the canvas, then resize the background image to fill the canvas. Modify the explosion location and size based on percentage of the canvas dimension.

Seven Thunder Software applies media queries to place the canvas and text area with buttons. When the browser viewing area has more width than height, the canvas displays to the right. The text and buttons display to the left. In other words the browser viewing area is in landscape mode.

When the browser viewing area has more height than width, the text and buttons display above the canvas. In other words the browser viewing area is in portrait mode.

The following listing demonstrates how Seven Thunder Software loads a base style sheet, and separate style sheets for landscape, portrait, wide, or narrow browser display areas. For example file sts-portrait.css stacks the canvas and text area full screen. File sts-landscape.css places the canvas and text area next to each other.

<style type="text/css">     
 @import url(styles/sts-base.css); 
</style>
  
<link rel="stylesheet"  
 type="text/css" 
 media="(orientation: portrait)" 
 href="styles/sts-portrait.css">

<link rel="stylesheet"  
 type="text/css" 
 media="(orientation: landscape)" 
 href="styles/sts-landscape.css">

<link rel="stylesheet"  
 type="text/css" 
 media="(max-width: 640px)" 
 href="styles/sts-narrow.css"> 
 
<link rel="stylesheet"  
 type="text/css" 
 media="(min-width: 640px)" 
 href="styles/sts-wide.css">
	

For simplicity sake, the following tutorial applies fixed sizes for images and canvas. Everything works and animation concepts remain the same.

Display the Background

To display the background create a JavaScript Image instance. Assign the src property to point to a file which represents the background. Assign an onload function to the Image instance. Once the background image has loaded, then draw the graphic on the canvas. In both examples the entire canvas displays the background image. The following listing demonstrates assigning and displaying the coffee pot graphic. After the graphic loads, draw the graphic edge to edge across the canvas. Variables I_BG_DIM_X and I_BG_DIM_Y represent the width and height of both the background images and the canvas for both examples. However developers can change values assigned to I_BG_OUT_X and I_BG_OUT_Y to expand or contract images as they draw to the canvas.

imgBG = new Image();

imgBG.src = "percolator-pot.gif";
...	
imgBG.onload = function() {	
	
context.drawImage(
 imgBG,
 0,0,
 I_BG_DIM_X,
 I_BG_DIM_Y,
 0,0,
 I_BG_OUT_X,
 I_BG_OUT_Y
);

};		
	

Start the Timer

When the user taps the canvas, the function runStart() assigns a timer to activate runAnimation() every 100 milliseconds. Function runAnimation() displays the background and sprites.

The following listing includes the entire runStart() function which starts the timer. Notice runStart() first stops the timer if needed. Variable N_TIME represents the number of milliseconds to wait between calls to function runAnimation().

function runStart(){ 

if (timer != null){
runStop();
} 

iCounter = new Number(0);

iLoopCounter = new Number(0);

timer = setInterval(

 function(){

  runAnimation();
 
 },

 N_TIME
 
);   
}

Display the Sprite Sheet

Draw one frame of the sprite sheet, per call to runAnimation(). Maintain an array of coordinates which represent the X and Y position of each frame of the sprite sheet. In the explosion examples variable A_IMG references a two dimensional array. The first dimension is the X coordinate, the second dimension is the Y coordinate.

Both explosion examples play the sprite sheet twice. Variable iLoops represents the number of times the sprite sheet explosion plays. Set iLoops to one. iLoops is zero based and therefore sets a boundary to play the animation once for loop 0 and once for loop 1.

When the animation has played twice then stop the timer, draw the background image, and return from the animation function.

The following listing tests to determine if the number of loops is greater than or equal to the loop boundary. If so, then call runStop(), draw the background image, and exit function runAnimation().

function runAnimation() {
...

if (iLoopCounter > = iLoops){

runStop();

context.drawImage(
 imgBG,
 0,
 0,
 I_BG_DIM_X,
 I_BG_DIM_Y,
 0,
 0,
 I_BG_OUT_X,
 I_BG_OUT_Y
);

 return;
}

...

}
	

Index into Array Counter

Be sure not to override the boundaries of the array. Store the maximum length of the array. Variable iIndex maintains the maximum length of the sprite sheet array. var iIndex = A_IMG.length-1;.

For each frame update an index into A_IMG; the array of coordinates. Variable iCounter tracks the current index into the coordinate array. During animation increment iCounter.

iCounter = iCounter + 1;.

Verify iCounter isn't greater than iIndex. If iCounter is greater than the length of the coordinate array, then reset the current index, redraw the background, and check the loop counter.

The entire runAnimation() function follows. Notice iCounter counts each frame and iLoopCounter counts each loop. Variables I_SPRITE_OUT_X and I_SPRITE_OUT_Y equal the same values as I_BG_DIM_X and I_BG_DIM_Y. However if developers want to expand or contract the images before drawing to the canvas, just change the values of I_SPRITE_OUT_X and I_SPRITE_OUT_Y.

Variable I_SPRITE_XY represents the location to place the sprite over the background image. The explosion appears at the same value for both X and Y coordinates. The sprite renders over the background image.

function runAnimation() {

 iCounter = iCounter + 1;

if (iCounter > iIndex){

if (iLoopCounter  >= iLoops){

runStop();   

 context.drawImage(
  imgBG,
  0,
  0,
  I_BG_DIM_X,
  I_BG_DIM_Y,
  0,
  0,
  I_BG_OUT_X,
  I_BG_OUT_Y
);

return;

}

else {

iLoopCounter++;

iCounter = 0;

context.drawImage(
 imgBG,
 0,
 0,
 I_BG_DIM_X,
 I_BG_DIM_Y,
 0,
 0,
 I_BG_OUT_X,
 I_BG_OUT_Y
 );

}

}

// I_SPRITE_XY
// represents
// the location
// to place the sprite
// over the background 
// image.
context.drawImage(
 imgSprite,
 A_IMG[iCounter][0],
 A_IMG[iCounter][1],
 I_SPRITE_X,
 I_SPRITE_Y,
 I_SPRITE_XY,
 I_SPRITE_XY,
 I_SPRITE_OUT_X,
 I_SPRITE_OUT_Y
);
  
}

Stop the Effect

Stop the timer when the user taps the Stop button or runAnimation() has displayed the explosion twice. Stop the timer with a call to the JavaScript API function clearInterval(...). Reset the timer to null. The following function runStop() stops the timer.

function runStop(){
 clearInterval(
  timer
 );
 timer = null;	
}	
	

Tips

Minimize the number of redraws to the canvas. Redrawing to the canvas can slow down mobile devices. Therefore each frame of the explosion effect is cumulative. The explosion effect was created on a PNG graphic with alpha transparency. Each frame of the explosion effect is drawn over the previous frame of the effect.

Drawing one frame over another means that code does not have to clear the entire canvas, redraw the background, then draw the current frame of the explosion.

The time between each frame, dimensions of the background, actual dimensions of each sprite frame, and output dimensions of each sprite frame remain constant throughout the animation. Code can reuse values within the array along with a set of unchanging variables. Constants aren't currently part of the JavaScript syntax. The source code uses upper case letters to indicate values which won't change during the course of the project.

Summary

This tutorial discussed how to animate a graphical explosion over a background image. We explained how to code an interactive explosion effect with sprite sheets, HTML5, the canvas element, and JavaScript. For more details see the Graphical Explosion Effect Source Code.

This tutorial covered three steps plus responsive Web design. First display a background graphic with just one frame. Second in response to a tap on the canvas, prepare a timer to draw sprites over the background graphic. Third display a sprite sheet with multiple frames for use as an explosion.

For an introduction to sprite sheets see the Beginner's Guide to Sprite Sheets Tutorial. To design the graphics see the Create Explosion Graphics Tutorial. See more HTML5 animation examples below.

More HTML5 Animation Examples

Edited (5/6/17)

Copyright © 2015 Seven Thunder Software. All Rights Reserved.