Small codes

HTML5, Javascript and AS3

Discover easeljs: animation and display list

| 4 Comments

In the previous post, I told you why Easeljs is a good library to start with HTML5 canvas when you come from the “Flash world”, and I posted my first script, a “hello world”.

This time, I’ll speed things up a bit, and we will first get acquainted with the Ticker() object to animate our “hello world” example. Then I’ll tell you a little about each display objects in Easeljs.

Note that I will now take advantage of the benefits of another universally known library: jQuery. It will be useful to load pictures and make selectors. Adding Jquery to our project is very simple: just add this line before the head tag of index.html page:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

One last word before I begin: I’ll talk much about Object Oriented Programming (OOP) from here. So I will use certain traditional terms, such as classes, objects, instances, inheritance or composition. These are important concepts order to use the most of Easeljs potential, and more generally to develop reusable and easy maintainable code.

If you want to refresh with OOP, you will find information on this well done tutorial or this wikipedia article. . I’ll develop more about OOP concepts in javascript in my next post.

The Ticker Object

The Ticker object is a Metronome. He will set the refresh rate of our animation. It’s a static class, and can’t be instantiated.
Here’s how to use it with my “Hello World!” example from the previous post:

(function(){
var stage;
var textfield;
var myCanvas = $("#stageCanvas").get(0);

this.init = function() {
	
	stage = new createjs.Stage(myCanvas);
	
	textfield = new createjs.Text("Hello World","bold 36px Courier","#fff");
	textfield.x = 400;
	textfield.y = 300;
	textfield.textAlign ="center";
	
	stage.addChild(textfield);
	stage.update();
    
    createjs.Ticker.setFPS(24);
    createjs.Ticker.addListener(this);
}
this.tick = function(){
    //The Ticker() object attempts to call this function 24 times per second;
    textfield.x += 4;
    textfield.rotation +=6;
    if ( textfield.x >900)  textfield.x =-100;
    stage.tick();
}
window.onload = init();
})();

First, the TextField variable has been upped at global scope, out of the init() function.
This allow us to reach it from any method in the main.js script.
Note that we also now define the myCanvas variable with jQuery selectors.

var textfield;
var myCanvas = $("#stageCanvas");

Then we called methods addListener () and setFPS () of the Ticker() class.
createjs.Ticker.setFPS(25) call the tick function 25 times per seconds (At least, the browser will try to).
createjs.Ticker.addListener(this) add a listener. In this case, “this” refers to the window object of the DOM.

createjs.Ticker.setFPS(32);
createjs.Ticker.addListener(this);

Following these instructions, the library will attempt to execute the tick() method 24 times per second at target scope: the window DOM object.

this.tick = function(){
}

Next, in this tick() function, we add 4 pixels to the x position of the the TextField object and 6 to it’s rotation value.
In order to be clean, we add a test on the x value, which is set to zero if it exceeds 900.
Following these changes, we execute the tick() method the stage object.

textfield.x += 4;
textfield.rotation +=6;
if ( textfield.x >900)  textfield.x =-100;
stage.tick();

Here’s the result

The display objects

The Stage class is a display class which serves as root for any other objects we add to it with the addChild () method. It is somewhat like scrapbooking! In this case, we added a Text() object, but there are other display objects in Easeljs, all specialized, that can be added to the display list.

Text()

The Text() object draws text in the canvas. Be careful, this text is just a bunch of pixels. It isn’t selectable, and totally escapes the search engines. If you work on a website, it’s not a good option. on the other hand, for a game, an animation or a small animated icon or graphic, it may be usefull.
Shape

A Shape object is like a blank page that may contain graphic forms. The forms are managed by a Graphics object (). To use a Shape object, first we have to create a Graphics object (). We then pass the Graphics object() as a parameter of the Shape object().

//Graphics() object creation
var graphic = new createjs.Graphics();
graphic.beginFill(Graphics.getRGB(255,255,255,1));
graphic.drawCircle(0,0,40);
//Shape() object creation with a Graphics() object as parameter. 
var shape = new createjs.Shape(graphic);
//add it to the Stage and update it 
stage.addChild(shape);
stage.update();

Bitmap

[Edit 2012-01-18]
The Bitmap object can display images, and handles all loading operations. The Ticker is essential here: it refreshes display at regular intervals, which allows the image to be displayed automatically when it’s upload is complete.
Here is one made ​​by me (^^), you can save it in the img folder in our sample site.
A beautifull spaceship
For this example, we will entirely rewrite the main.js file:

(function(){
//create variables at global scope 
var stage;
var myCanvas = $("#stageCanvas");
var bitmap;

this.init = function(){
	stage = new createjs.Stage(myCanvas);
	//Bitmap() object creation with image path as parameter
        bitmap = new createjs.Bitmap( "img/car.png");
        bitmap.x = 400;
        bitmap.y = 300;
        stage.addChild(bitmap);
	stage.update();
	
	createjs.Ticker.setFPS(32);
	createjs.Ticker.addListener(this);
}
this.tick = function(){
  stage.update();
}
})();

Et voila !
We will see in an upcoming post how to create a preloader for all images of our animation.

SpriteSheet

The SpriteSheet() object controls an animated Sprite. This class may be used with a very handy tool created by G. Skinner, called Zoe. Zoe is an AIR application that turns a Flash scenario into a SpriteSheet: an image composed of all frames of a sprite animation.
Once the image is created, the SpriteSheet() object can use it, by decomposing the different movements of the sprite.
You can download Zoe here, if you want to play with it.For now, I will not go further on SpriteSheet … But we’ll talk about it later.

Container

The object Container, finally, can be used as a Stage in the Stage.
Let me explain: You can create a Container(), and add text, shape, and an image. Then you can move or rotate the container, and this movement will be applied to all child objects of the container.

Here is a practical example: we will create an icon.
We will resume our example of image loading, but we will create a rounded rectangle behind it and a text below. Then we will add these three elements in a Container(). Finally, we will add the Container() to the scene and animate it.

(function(){
var stage;
var myCanvas = $("#stageCanvas").get(0);
var bitmap;
var graphic;
var roundRectangle;
var icon;
var text;
this.init = function(){
      
	stage = new createjs.Stage(myCanvas);
	
        graphic = new createjs.Graphics();
        graphic.beginFill(Graphics.getRGB(125,200,255,1));
        graphic.drawRoundRect(-30,-30,60,60,4);
        roundRectangle= new createjs.Shape(graphic);

        bitmap = new createjs.Bitmap("img/car.png");
        bitmap.x = -bitmap.image.width*.5;
	bitmap.y = -bitmap.image.width*.5;
		
	text = new createjs.Text("Icon", "bold 16px Courier","#fff");
	text.textAlign="center";
	text.y = 50;
	
        //Container creation
        icon = new createjs.Container();
        
        //add the shape, text and image as child of the Container() object 
        icon.addChild(roundRectangle);
        icon.addChild(bitmap);
	icon.addChild(text);
        icon.x = 400;
        icon.y = 300;
        stage.addChild(icon);
	stage.update();
		
	createjs.Ticker.setFPS(32);
	createjs.Ticker.addListener(this);
}
this.tick = function(){
  icon.rotation +=2;
  stage.update();
}
window.onload = init();
})();

Here’s the result.

Containers are extremely useful for creating complex objects.

DisplayObject

The DisplayObject () in Easeljs is a class that you will almost never use directly.
This is actually the parent class of all those we have just seen. The Text(), Shape(), Bitmap() and even Stage() all inherit from the DisplayObject() class. It gives basic properties to our display objects, such as. x,.y,. height,. width.

In the next post I will talk about some concept of object-oriented programming, starting from the last example.

4 Comments

  1. Pingback: Discover EaselJS - OOP and complex objects creation | small codes

  2. Très bonne suite du premier tutoriel on est vraiment pas depaysé quand on a fait de l’ActionScript 3 !

    Pour les SpriteSheet il y a de quoi bien partir avec ce lien : http://blogs.msdn.com/b/davrous/archive/2011/07/22/jeux-html5-animation-de-sprites-dans-l-233-l-233-ment-canvas-gr-226-ce-224-easeljs.aspx

  3. Très bon tutoriel, mais qui maleureusement est truffé d’erreurs. Par exemple:

    bitmap = new Bitmap(“img/car.png”);
    bitmap.x = 0-img.width*0.5;
    bitmap.y = 0-img.height*0.5;

    Tu ne définis aucunement la variable img. Pour cause, lorsque je teste ce code, il me relève une erreur, à selon laquelle je dois la remplacer par une valeur numérique.

    Autre erreur (et là je copie-colle):

    (function(){
    var stage;
    var myCanvas = $(“#stageCanvas”).get(0);
    //création des variables au niveau global de notre script
    var bitmap;

    this.init = function(){
    stage = new Stage(myCanvas);
    //Création de l’objet Bitmap() avec le chemin de l’image en paramètre, et ajout à la liste d’affichage
    bitmap = new Bitmap( “img/car.png”);
    bitmap.x = 400;
    bitmap.y = 300;
    stage.addChild(bitmap);
    stage.update();

    Ticker.setFPS(32);
    Ticker.addListener(this);
    }
    this.tick = function(){
    stage.update();
    }

    Tu oublie, à la dernière ligne de ton code de refermer les parenthèses de ta fonction primaire.

    Quand on fait un tutoriel de code, on doit s’assurer toujours de se relire et au minimum tester chaque morceau de code présenté.

    • Merci d’avoir pointé ces 2 petites coquilles. La seconde est due à un copier-coller un peu rapide…
      La première avait déjà été corrigée dans l’exemple, mais la correction n’avait pas été reportée sur le tuto.

      La bonne syntaxe pour le cadrage est donc :

      bitmap.x = -28;
      bitmap.y = -24;

      Mes excuses pour ceux qui ont perdu du temps à cause de ça. C’est corrigé !

      Mais… “truffé d’erreurs” c’est un peu fort, non ? Pour le reste je suis d’accord avec toi ;)

Leave a Reply

Required fields are marked *.


Social Widgets powered by AB-WebLog.com.