HTML5 Hidden Object Games: Create Interactive Images

Background Animation Tutorial

Animated Panoramic Backgrounds

Introduction

This tutorial explains how to design and develop animated panoramic backgrounds with the HTML5 canvas. This article also discusses a method to optimize background animation. Create graphics and code which work together.

Animated backgrounds provide the opportunity to display online environments such as panoramic photographs, 3D generated renderings, 360 degree architectural views, and actual digital space scenes such as the Mars interactive scene.

Interactive backgrounds extend concepts discussed in this tutorial. Interactive backgrounds offer useful techniques for online games and scientific visualization.

What's an Animated Panoramic Background?

Panoramas represent wide views of practically any scene. Panoramic backgrounds may display circular or 360 degree views of various environments. For example, assume you were standing on the edge of the Grand Canyon with a crowd behind you. Photograph a 360 degree view of the Grand Canyon scene. The photograph would include the grand canyon from the left, to the right, and everything behind you including the crowd. However animated panoramas can cover any part part of a scene you choose, such as the grand canyon without the crowd.

Consider animated backgrounds with a concept from the real world. Imagine sliding a long horizontal picture past a small rectangular window. The window represents the HTML5 canvas. The picture represents a digital panoramic image. For animation which doesn't loop, just slide the picture from left to right. For loops, slide the picture from left to right then begin again at the left side.

Loops create the appearance of continual circular motion from front to left, back, right, then to the front of the scene again. The left side and the right side of the picture should match seemlessly for smooth animated loops. This tutorial explains how to create seamless looping animation.

HTML5 background animation includes a canvas, graphic, and timed drawing of the graphic to the canvas. Sprite sheet animation uses similar concepts. In both cases the canvas is much smaller than the graphic. However with sprite sheets each frame displays one unique rectangular portion of the graphic. With panoramic animation the canvas displays the graphic as if the image were sliding behind the canvas. Any rectangular portion of the graphic can represent one frame. Panoramic backgrounds require smaller image files which use less memory. Therefore panoramic backgrounds can provide better performance than sprite sheet animation.

For example assume the panoramic image is 1024 pixels wide and 256 pixels high. Assume the canvas is 300 pixels wide and 256 pixels high. The first frame displays the first 300 pixels from the left edge of the panoramic graphic. A cut out shows the first 300 pixels wide by 256 pixels high section of the panorama. Pixels 301 through 1024 along the horizontal axis of the panoramic graphic would remain hidden for the first frame.

Define a box with the first set of coordinates representing the upper left hand corner and the second set of coordinates representing the lower right hand corner. The first cut out within the panoramic graphic begins at coordinates (0,0) and ends at coordinates (300, 256).

The animation displays one frame for every four pixels from the panorama. Therefore increment an index by four for each frame. The index represents the X (horizontal) coordinate of the panoramic graphic. As the index increases, the image displayed in the cut out moves along the X axis. The user sees different sections of the scene.

The second frame displays a cut out of the panoramic image from the 4th pixel to the 304th pixel along the horizontal axis. Therefore the second frame renders a rectangle from coordinates (4,0) to (304,256).

Prepare the Graphics

The 3D Landscape Panoramic Graphic

3D Landscape Panorama

Full 360 degree panoramic graphics can be prepared with 3D rendering software, 360 degree panoramic cameras, or 2D image editing applications. The two examples use a 360 degree image of Mars from the NASA website and a 3D landscape rendered and modeled with 3DS Max.

Animations which play in a loop require graphics which stitch together seamlessly. The graphic wraps around from the back of the panorama to the front of the panorama.

Assuming a column equals four pixels of a panoramic graphic. The last column of a panoramic image renders adjacent and to the left of the first column during a seamless loop. The two endpoints of the graphic should look like one frame of the scene. A panoramic graphic for a looping animation should tile otherwise the start of each loop appears to jump.

Prepare Graphics to Work with Code

This tutorial focuses on preparing graphics to work with code rather than code to work with graphics. The graphics were custom designed to reduce the amount of processing required with JavaScript. Well designed graphics provide faster animation. This tutorial explains how to prepare panoramic graphics for faster processing.

To make the graphic work efficiently with JavaScript, create an overlap at the end of the panorama. Toward the end of the animation, part of the end of the panoramic view and part of the start of the panoramic view display. Part of both ends of the panoramic view render to the canvas.

Tradeoff Between Memory and Processing Power

Some tutorials recommend slicing pixels in columns. Splice together the front and back back of a panoramic image, during animation for each overlapping frame. This tutorial copies the front cut out to the back of the panoramic image in advance. Then save and load a wider image. With a larger graphic, the animation requires more memory yet fewer processing instructions.

When the index into the panoramic graphic nears the end of the panorama, JavaScript simply continues to display the graphic. When the index into the panoramic graphic is at the end, JavaScript displays the front cut out. There's no automated seam or splicing, but there is some repetition in the graphic. The last cut out and the first cut out have to be identical, otherwise animation displays a noticeable shift.

The end (or right most) section of the cut out displays portions of the graphic which are identical to the front (or left most) section of panoramic image.

3DS Max Panorama Exporter

The graphic at the top of the page was modeled and rendered with 3DS Max. A camera was placed in the center of the scene. The image was rendered with the Panorama Exporter. From 3DS Max's top menu select Rendering > Panorama Exporter. In the Interactive Panorama Exporter Parameters rollout, select the centered camera. Select a dimension for each face of the cube. Tap the Render button. The Panorama Exporter renders the scene as six sides of a cube. After the scene has rendered the Panorama Exporter Viewer displays. From the viewer's top menu, select File > Export > Export Cylinder.

The cylinder graphic represents the scene as if it were wrapped inside a cylinder. Some of the scene might need some modifications for better viewing on a flat surface. When the scene's ready for animation, copy the far right side of the panoramic image to the left side of the graphic.

The following graphic identifies identical sections along the far left side of the graphic and far right side of the graphic. The JavaScript explanation follows.

How JavaScript Displays the Background Animation

Diagram Left and Right Side of Panorama

The function loadAnimation() executes when the page loads. Function loadAnimation() obtains a reference to the 2d context then creates an Image reference. Assign the path and name of your panoramic graphic to the image's src property. Additionally assign an onload event listener to the Image.

Wait until the image loads before drawing to the canvas. Attempting to draw an Image to the canvas before the Image loads generates exceptions. The onload event listener draws the Image only after the graphic loads.

Avoid Scaling

Cut outs from the graphic are 300 x 256 pixels. Drawing operations can scale up or down. For example you might double the display size from 300 x 256 to 600 x 512. HTML5 allows scaling when rendering with method drawImage(). However scaling decreases performance which might slow down the animation. With this example, JavaScript performs calculations for each frame. Sometimes it's better to avoid scaling during animation sequences to provide better performance.

Consider loading larger indexed, eight bit graphics to display larger animation frames. Perhaps test browsers and devices to determine which combination works best for performance.

Method drawImage()

drawImage() is a predefined method of the HTML5 canvas 2D context. The following listing demonstrates drawing a section of the graphic to the canvas when the graphic loads. When the Image loads the first frame of the animation displays.

The first parameter to drawImage() references the panoramic Image. The second, third, fourth, and fifth parameters describe a rectangle within the panoramic graphic. The rectangle is the portion of the graphic to draw to the scene. The second and third parameters provide X and Y coordinates of the upper left hand corner to begin drawing. The fourth and fifth parameters provide the width and height of the rectangle to draw.

The sixth, seventh, eight, and ninth parameters describe a rectangle within the canvas. The rectangle is the portion of the canvas to update.

Variables N_WIDTH and N_HEIGHT represent the canvas width and height as well as the graphic width and height.

context.drawImage(
 imgSprite,
 0,0,
 N_WIDTH,
 N_HEIGHT,
 0,0,
 N_WIDTH,
 N_HEIGHT
);	
	

Start and Stop Animation

Functions animStart() and animStop() respond to click events on the Start and Stop buttons. Additionally function animStartStop() toggles the animation between start and stop modes. Tap the canvas to toggle the animation mode.

The Start button initializes the timer to call the function animPlay() every 64 milliseconds. The Stop button calls clearInterval() and sets the timer to null.

Run the Animation

The function animPlay() increments an index into the graphic. Function animPlay() displays one cut out or frame to the canvas with a call to method drawImage(). Preparing graphics beforehand optimized the code. That's good because animPlay() runs often and does very little.

The following listing includes the entire animPlay() function. First animPlay() increments the Number nPan by N_INCREMENT. This example moves the panoramic graphic four pixels per frame. Therefore N_INCREMENT is a Number with the value 4.

Second verify nPan hasn't exceeded the available drawing width. Variable nPan should not be greater than the width of the panoramic graphic minus the width of one cut out. The Number N_PAN_MAX equals the entire width of the panoramic graphic minus the width of one animation frame. If nPan exceeds N_PAN_MAX, then reset nPan to zero.

Third draw the panoramic graphic to the scene. Notice nPan defines the X coordinate of the upper left corner of the area of the panoramic graphic to draw to the canvas. For each animation frame, the X coordinate of the upper left corner changes.

function animPlay(){
 
 nPan += N_INCREMENT;

 if (nPan == N_PAN_MAX){

  // Wrap around.
  // Display the left
  // side of the graphic.
  nPan = 0;
  
 }

// Draw one slice of 
// the panoramic
// background.
context.drawImage(
 imgSprite,
 nPan,0,
 N_WIDTH,
 N_HEIGHT,
 0,0,
 N_WIDTH,
 N_HEIGHT
 ); 
}

Tips

This tutorial demonstrated how to animate a horizontal background. However consider animating vertical backgrounds with similar techniques. Perhaps horizontal, vertical, diagonal, and random selections from a background graphic might present some fascinating and unique interactive scenes. A properly constructed graphic is the key. The graphic should tile seamlessly along any edges which represent a loop in the animation.

Be careful to initialize only one timer during any animation sequence. JavaScript allows multiple timers to run at the same time. However each timer consumes resources. Set the timer to null when stopped to prevent animStart() from initializing multiple timers.

Summary

This tutorial explained how to design and develop animated panoramic backgrounds with the HTML5 canvas. This article also discussed a method to optimize background animation. Create graphics and code which work together.

Animated backgrounds provide the opportunity to display online environments such as panoramic photographs, 3D generated renderings, 360 degree architectural views, and actual digital space scenes such as the Mars interactive scene.

The Martian Interactive Background Tutorial extends concepts discussed in this tutorial. Interactive backgrounds offer useful techniques for online games and scientific visualization.

Enjoy the next step! See the Mars interactive scene with tutorial. See More Background Scenes.

More Background Scenes

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