HTML 5游戏:EaselJS创建Canvas动画

When you want to write casual games using the HTML5 Canvas element, you’ll need to find a way to handle your sprites. There are several libraries available to help you writing games such as ImpactJSCraftyJS and so on. On my side, I’ve decided to use EaselJS which has been used to writePiratesLoveDaisies: an HTML5 Tower Defense game. This awesome library works in all modern HTML5 browsers and could even help you building a Windows 8 Metro Style Applications HTML5 games.

For instance, if you’re running the Windows 8 Consumer Preview, you can install the Pirates Love Daisies game from the Windows Store here: Pirates Love Daisies for Windows 8

In this first article, we’re going to see how to use your existing sprite elements and animate them.

Pour ceux qui pratiquent la langue de Molière, vous trouverez une version française ici : Jeux HTML5: animation de sprites dans l’élément Canvas grâce à EaselJS

This article is the first of a serie of 3:

- HTML5 Gaming: animating sprites in Canvas with EaselJS 
HTML5 Gaming: building the core objects & handling collisions with EaselJS 
HTML5 Platformer: the complete port of the XNA game to <canvas> with EaselJS

Introduction

On the official EaselJS site, you’ll find some interesting samples and some basic documentation. We will use the sprites sample as a base. We will use also the resources available in the XNA 4.0 Platformer sample. For those of you who are following my blog, you may remember that I love playing with this sample. Here are the previous attached articles:

Windows Phone 7 Platformer Starter Kit for XNA Studio 4.0 
Silverlight 4 XNA Platformer Level Editor for Windows Phone 7

The platformer sample have been updated in the meantime by our XNA team and is available here for Xbox 360, PC & Windows Phone 7: App Hub – platformer . You can download it to play with it and extract the sprites to use them with EaselJS.

In this article, we’re going to use these 2 PNG files as source of our sprite sequences:

Our monster running:


which contains 10 different sprites.

Our monster in idle mode:

which contains 11 different sprites.

Note: The following samples have been tested successfully in IE9/IE9 Mobile/IE10 PP5/Chrome 17 & Firefox 11. It doesn’t work in Opera due to a bug in their native Image implementation apparently: About Issue in latest Opera  

Tutorial 1: building the SpriteSheet and the BitmapAnimation

We’ll start by moving the running monster between the beginning and the end of the width of our canvas.

First step is to load the complete sequence contained in the PNG file via this code:

View Code
var imgMonsterARun = new Image();

function init() {
    //find canvas and load images, wait for last image to load
    canvas = document.getElementById("testCanvas");

    imgMonsterARun.onload = handleImageLoad;
    imgMonsterARun.onerror = handleImageError;
    imgMonsterARun.src = "img/MonsterARun.png";
}

This code will be called first to initialize our game’s content. Once loaded, we can start the game. EaselJS expose a SpriteSheet object to handle the sprite. Thus, by using this code:

View Code
// create spritesheet and assign the associated data.
var spriteSheet = new SpriteSheet({
    // image to use
    images: [imgMonsterARun], 
    // width, height & registration point of each sprite
    frames: {width: 64, height: 64, regX: 32, regY: 32}, 
    animations: {    
        walk: [0, 9, "walk"]
    }
});

We’re indicating that we’d like to create a new sequence named “walk” that will be made of the imgMonsterARun image. This image will be split into 10 frames with a size of 64x64 pixels. This is the core object to load our sprites and create our sequences. There could be several sequences created from the same PNG file if you want to, like in the rats sprite sample of the EaselJS site.

After that, we need to use the BitmapAnimation object. It helps us animating our sequence and positioning our sprites on the screen. Let’s review the initializing code of this BitmapAnimation:

View Code
// create a BitmapAnimation instance to display and play back the sprite sheet:
bmpAnimation = new BitmapAnimation(spriteSheet);

// start playing the first sequence:
bmpAnimation.gotoAndPlay("walk");     //animate
    
// set up a shadow. Note that shadows are ridiculously expensive. You could display hundreds
// of animated rats if you disabled the shadow.
bmpAnimation.shadow = new Shadow("#454", 0, 5, 4);

bmpAnimation.name = "monster1";
bmpAnimation.direction = 90;
bmpAnimation.vX = 4;
bmpAnimation.x = 16;
bmpAnimation.y = 32;
        
// have each monster start at a specific frame
bmpAnimation.currentFrame = 0;
stage.addChild(bmpAnimation);

The constructor of the BitmapAnimation object simply needs the SpriteSheet element as a parameter. We’re then giving a name to the sequence, setting some parameters like the speed and the initial position of our first frame. Finally, we add this sequence to the display list by using the Stageobject and its addChild() method.

Next step is now to decide what we’d like to do in our animation loop. This animation loop is called every xxx milliseconds and let you update the position of your sprites. For that, EaselJS exposes a Ticker object which provides a centralized tick or heartbeat broadcast at a set interval. If you’re looking to the Ticker.js source code, you’ll see that the Ticker object of EaselJS 0.4 now supports requestAnimationFrame() :

View Code
var f = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame ||
                window.oRequestAnimationFrame || window.msRequestAnimationFrame;

Thanks to this code, IE10, Firefox, Chrome and future versions of Opera are supported already. But it’s not used by default by EaselJS. Probably for compatibility reasons I guess.

You can request to use it (for possible more efficient animations) via the boolean property useRAF set to true. Don’t worry, if your browser doesn’t support it, the code will automatically falls back to the setTimeout() method.

Ok, all you’ve got to do now is to subscribe to the tick event and implement a .tick() method that will be called back. This code is for instance registering the event on the global window object:

View Code
Ticker.addListener(window);
Ticker.useRAF = true;
// Best Framerate targeted (60 FPS)
Ticker.setInterval(17);

And here is the code that will be called every 17ms (in an ideal world) to update the position of our monster:

View Code
function tick() {
    // Hit testing the screen width, otherwise our sprite would disappear
    if (bmpAnimation.x >= screen_width - 16) {
        // We've reached the right side of our screen
        // We need to walk left now to go back to our initial position
        bmpAnimation.direction = -90;
    }

    if (bmpAnimation.x < 16) {
        // We've reached the left side of our screen
        // We need to walk right now
        bmpAnimation.direction = 90;
    }

    // Moving the sprite based on the direction & the speed
    if (bmpAnimation.direction == 90) {
        bmpAnimation.x += bmpAnimation.vX;
    }
    else {
        bmpAnimation.x -= bmpAnimation.vX;
    }

    // update the stage:
    stage.update();
}

You can test the final result here:

EaselJS Sprites Tutorial 01

You can also browse this sample here: easelJSSpritesTutorial01 if you’d like to view the complete source code.

But wait! There are 2 problems with this animation:

1 – the animation steps are weird as the character seems to loop through its different sprites sequence too fast 
2 – the character can only walk normally from right to left otherwise it looks like it tries to achieve a kind of Moonwalk dance. Clignement d'œil

Let’s see how to fix that in the second tutorial.

Tutorial 2: controlling the animation speed and flipping the sprites

To fix the animation’s speed, the simplest way to do it is to change the frequency parameter of the animations object of your SpriteSheet object like slightly described in the documentation: SpriteSheet . Here is the new code to build the SpriteSheet:

var spriteSheetIdle = new SpriteSheet({
    images: [imgMonsterAIdle],
    frames: { width: 64, height: 64, regX: 32, regY: 32 }, 
    animations: {
        idle: [0, 10, "idle", 4]
    }
});

You’ll need also to slow down the velocity by changing the vX from 4 to 1 (logically divided by 4).

To add new animation frames to let the character walking normally from left to right, we need to flip each frame. EaselJS exposes a SpriteSheetUtilsobject for that and a addFlippedFrames() method you’ll find in the source. Here is my code that uses that:

SpriteSheetUtils.addFlippedFrames(spriteSheet, true, false, false);

We’re creating a derivative sequence that will be named “walk_h based on the “walk” sequence that we’re flipping horizontally. At last, here is the code that handles which sequence we should play based on the character position:

View Code
function tick() {
    // Hit testing the screen width, otherwise our sprite would disappear
    if (bmpAnimation.x >= screen_width - 16) {
        // We've reached the right side of our screen
        // We need to walk left now to go back to our initial position
        bmpAnimation.direction = -90;
        bmpAnimation.gotoAndPlay("walk")
    }

    if (bmpAnimation.x < 16) {
        // We've reached the left side of our screen
        // We need to walk right now
        bmpAnimation.direction = 90;
        bmpAnimation.gotoAndPlay("walk_h");
    }

    // Moving the sprite based on the direction & the speed
    if (bmpAnimation.direction == 90) {
        bmpAnimation.x += bmpAnimation.vX;
    }
    else {
        bmpAnimation.x -= bmpAnimation.vX;
    }

    // update the stage:
    stage.update();
}

You can test the final result here:

 

You can also browse this sample here: easelJSSpritesTutorial02 if you’d like to view the complete source code.

Tutorial 3: loading multiple sprites and playing with multiple animations

It’s time now to load the idle state of the monster. The idea here is to play the walking animation once to achieve a single round-trip. Once achieved, we will play the idle state.

We will then now load multiple PNG files from the web server. It’s then very important to wait until all resources are loaded otherwise you may try to draw non-yet downloaded resources. Here is a very simple way to do it:

View Code
var numberOfImagesLoaded = 0;

var imgMonsterARun = new Image();
var imgMonsterAIdle = new Image();

function init() {
    //find canvas and load images, wait for last image to load
    canvas = document.getElementById("testCanvas");

    imgMonsterARun.onload = handleImageLoad;
    imgMonsterARun.onerror = handleImageError;
    imgMonsterARun.src = "img/MonsterARun.png";

    imgMonsterAIdle.onload = handleImageLoad;
    imgMonsterAIdle.onerror = handleImageError;
    imgMonsterAIdle.src = "img/MonsterAIdle.png";
}

function handleImageLoad(e) {
    numberOfImagesLoaded++;

    // We're not starting the game until all images are loaded
    // Otherwise, you may start to draw without the resource and raise 
    // this DOM Exception: INVALID_STATE_ERR (11) on the drawImage method
    if (numberOfImagesLoaded == 2) {
        numberOfImagesLoaded = 0;
        startGame();
    }
}

This code is very simple. For instance, it doesn’t handle the errors properly by trying to re-download the image in case of a first failure. If you’re building a game, you will need to write your own content download manager if the JS library you’re using doesn’t implement it.

To add the idle sequence and setting the position parameters, we just need to use the same kind of code previously seen:

View Code
// Idle sequence of the monster
var spriteSheetIdle = new SpriteSheet({
    images: [imgMonsterAIdle],
    frames: { width: 64, height: 64, regX: 32, regY: 32 }, 
    animations: {
        idle: [0, 10, "idle", 4]
    }
});

bmpAnimationIdle = new BitmapAnimation(spriteSheetIdle);

bmpAnimationIdle.name = "monsteridle1";
bmpAnimationIdle.x = 16;
bmpAnimationIdle.y = 32;
Now, in the tick() method, we need to stop the walking animation once we’ve reached back the left side of the screen and to play the idle animation instead. Here is the code which does that:

if (bmpAnimation.x < 16) {
    // We've reached the left side of our screen
    // We need to walk right now
    bmpAnimation.direction = 90;
    bmpAnimation.gotoAndStop("walk");
    stage.removeChild(bmpAnimation);
    bmpAnimationIdle.gotoAndPlay("idle");
    stage.addChild(bmpAnimationIdle);
}

You can test the final result here:

You can also browse this sample here: easelJSSpritesTutorial03 if you’d like to view the complete source code.

That’s all folks! But if you want to go further, you can read the next part here: HTML5 Gaming: building the core objects & handling collisions with EaselJS which is the second step you need to understand before writing a complete platform game detailed in the third article.

David

Note : this tutorial has originally been written for EaselJS 0.3.2 in July 2010 and has been updated for EaselJS 0.4. For those of you who read the version 0.3.2, here are the main changes for this tutorial to be aware of:

  1. BitmapSequence is not available anymore in 0.4 and has been replaced by BitmapAnimation
  2. You can now slow down the animation loop of the sprites natively while building the SpriteSheet object
  3. EaselJS 0.4 is now using requestAnimationFrame for more efficient animations on supported browsers (like IE10+, Firefox 4.0+ & Chrome via the appropriate vendors’ prefixes).

 

 

 

摘自:http://blogs.msdn.com/b/davrous/archive/2011/07/21/html5-gaming-animating-sprites-in-canvas-with-easeljs.aspx

 
 

posted on 2012-06-13 16:28  djy_fn  阅读(1248)  评论(0编辑  收藏  举报

导航