Online Book Reader

Home Category

HTML5 Canvas [187]

By Root 6347 0
a white color, and then saves it to the stack. We then translate to the center of our object and rotate the canvas by the current ctr value (an increment of 10). Next, we draw the first tile from mediumrocks.png and save the result into a new local imageData instance using the getImageData() function.

NOTE

This is the place where the security error will be thrown if the domain of the image and the domain of the HTML file are not the same. On a local machine (not running on a local web server, but from the filesystem), this error will be thrown on all browsers but Safari (currently).

Finally, the new imageData is pushed into the rotationImageArray. When the loop is complete, we set up an interval to run and call the drawScreen() function every 100 milliseconds.

To display the animation on the first canvas, we use this timer loop interval and call putImageData() to draw each frame in succession, creating the simulation of animation. As with the tile sheet, we didn’t have to use 36 frames of animation, we could use just five. Naturally, the animation is much smoother with more frames. But this process shows how easy it is to create simple transformation animations “on the fly” rather than precreating them in image files:

function drawScreen() {

//context.fillStyle = "#ffffff";

//context.fillRect(50,50,32,32);

context.putImageData(rotationImageArray[animationFrame],50,50);

animationFrame++;

if (animationFrame ==rotationImageArray.length){

animationFrame=0;

}

}

Example 9-2 shows the entire code.

Example 9-2. A dynamic tile sheet example

CH9EX2: Canvas Copy

Your browser does not support the HTML 5 Canvas.

Your browser does not support HTML5 Canvas.

In the rest of the chapter, we will look at creating a simple tile-based game using some of the techniques first discussed in Chapter 4.

A Simple Tile-Based Game

Let’s move from Asteroids to another classic game genre, the tile-based maze-chase game. When you’re discussing early tile-based games, undoubtedly Pac-Man enters the conversation. Pac-Man was one of the first commercially successful tile-based games, although it certainly was

Return Main Page Previous Page Next Page

®Online Book Reader