Javascript

EaselJS is a Javascript library that allows the programmer to work on html canvas in an easy way. It means that EaselJS abstracts the low level API of the canvas element and provides classes, structures and functions to manipulate visual elements.

Before starting the examples and the talk about the Easel modules, let’s set up the html file which will be used as basis throughout this post. Create a file called easel.html and copy the following code:

<!DOCTYPE html>
<html>
<head>

<script src="http://code.createjs.com/easeljs-0.7.1.min.js"></script>

<script>
    function init() {
        var canvas = document.getElementById('canvas')
        var stage = new createjs.Stage(canvas);
        // CODE HERE!
    }
</script>
</head>
<body onLoad="init();">

<canvas id="canvas" width="600" height="300">alternate content</canvas>

</body>
</html>

 The Basics

EaselJS provides a whole architecture to control the objects that will be used at our games. The following list explains a bit of each one of the core components of this architecture.

  • EventDispatcher: the EventDispatcher class provides the structure for managing queues of events listeners and dispatching events. All components of EaselJS inherit from this class, thus, any component can handle events such as mouse clicks, drags, etc. For example, you can register a callback function to the ‘click’ event of a Bitmap object, causing the callback to be called whenever the user clicks that Bitmap.
  • DisplayObject: is the base class for all visual element, exposing properties such as position, rotation, scale and transparency. It means that, you can manipulate the position, rotation and other display properties of any object that draws something at the screen.
  • Container: The Container inherit from DisplayObject and provides methods to group other DisplayObjects. Using Containers, you can create hierarchy of visual objects and manipulate them together. For example, if you have a container within 3 images and move the container to the left, all the three images will be moved to the left too.
  • Stage: the Stage is the root level of the DisplayObject hierarchy, thus, if you want to show an object in canvas you need to add this object to the stage.

After adding objects to stage, you need to call the stage “update” method, otherwise the canvas will be redraw and you won’t see any change. All examples below show how to use it.

Working with Shapes

A Shape object stores a group of vector graphics that are created directly by the canvas element. Each shape has a Graphics instance which is the interface to the canvas drawing system. Check the example below.

var shape = new createjs.Shape();
shape.graphics.beginFill('#99f');
shape.graphics.drawRect(0, 0, canvas.width, canvas.height);

shape.graphics.beginFill('#33f');
shape.graphics.beginStroke('black');
shape.graphics.drawCircle(canvas.width/2, canvas.height/2, 50);

stage.addChild(shape);
stage.update();

Notice how the graphics instance does the hard work. The beginFill function sets the filling color for the next drawings while beginStroke sets the stroke color. The Graphics object provides several functions for the drawing itself, take a look at the official documentation to see how drawRect, drawCircle and other directives work.

Working with Texts

With Text objects you can draw… texts! But just plain texts, not HTML-formatted ones. EaselJS allows you to change the color, alignment, size, font, wrapping and others settings of Text objects, check the official documentation to know more:

var text = new createjs.Text('Hello, World!', '32px Arial', '#53f');
text.textAlign = 'center';
text.x = canvas.width/2;
text.y = canvas.height/2;

stage.addChild(text);
stage.update();

Working with Bitmaps

With Bitmap objects you can display an image, canvas or video (the HTML elements) into the canvas. You can instantiate the Bitmap object using the HTML element explicitly or passing a string, as shown in the example. Notice that, the first lines of the code below is a bit different from the examples above, that is because I am using a external resource (the image ‘assets/html5.png’) and we can use it before the browser totally load it. This process is automated by PreloadJS.

img = new Image();
img.src = 'assets/html5.png';
img.onload = function(event) {
    var bitmap = new createjs.Bitmap('assets/html5.png');
    bitmap.x = canvas.width/2 - bitmap.image.width/2;
    bitmap.y = canvas.height/2 - bitmap.image.width/2;

   stage.addChild(bitmap);
   stage.update();
}

Consult the documentation to know more about bitmaps:

 Working with SpriteSheets

A sprite sheet is a group of several images combined into a single larger file, e.g.:Bubbles Sprite SheetYou can also define animations using sprite sheets as shown in the example.

EaselJS provides the SpriteSheet class to handle this kind of image.  The SpriteSheet object requires some configuration to work, such as the size of each frame and the sequence of animations, check the documentation for a detailed description of each property:

img = new Image();
img.src = 'http://static.guineashots.com/tutorials/easeljs/assets/bubbles.png';
img.onload = function(event) {
    var data = {
        framerate: 10,
        images: [img],
        frames: {width:64, height:64, regX:32, regY:32},
        animations: {
            'explode': [0, 10],
        }
    }

    var spritesheet = new createjs.SpriteSheet(data);
    var animation = new createjs.Sprite(spritesheet, 'explode');
    animation.x = canvas.width/2;
    animation.y = canvas.height/2;

    stage.addChild(animation);

    createjs.Ticker.addEventListener("tick", update);
    function update(event) {
        stage.update();
    }
}

The SpriteSheet only represents the sequence of images, to see them as isolated images or animations you need a Sprite.

Notice that, in the last lines of example, I register a function “update” to the “tick” event, so it will be called every frame by Easel. In this function I call the stage update so it can redraw the canvas and show each frame of our animation.

Other Tutorials

To learn more about EaselJS, follow the official tutorials:

Read more

Almost all games needs to record certain information about the player progression. For example, you may want to have a local leaderboard to track the player best results of each round, or the story progression, or the name of the player, etc. Sometimes is interesting to record these kind of information even after the user closes the browser and turn off the computer, thus, the next time a user comes back to your game, the progression is saved there.

HTML5 provides a feature for this kind of offline storage, called Local Storage. The concept is similar to cookies: you have a key-value storage system and you can write or read information locally with it. It is really basic, all you have to do is:

localStorage['key'] = 'value'

and you have an information stored in the user computer. The user can close the browser and turn off the computer but when he or she opens you game again, the information ‘key = value’ is still there.

The problem is when the browser does not support the HTML5 Storage feature. When this is the case, you need to use a third party library for offline storage, store the information into some server, or don’t save the information at all. The third option is the easier (if storing information is not essential), because you don’t have to change all your code, just define a stub localStorage object and the life goes on.

A beautiful way to detect if browser supports localStorage or any other HTML5 feature is using the Modernizr library. Thus, you can add the following verification to your code:

if (!Modernizr.localstorage) {
    window.localStorage = {};
}

Take a look at http://html5demos.com/storage to see an example.

Read more

I created a new repository in Github with my personal boilerplate to CreateJS. This boilerplate includes:

  • A simple server written in Python using the Flask web framework, you will need them to run the server;
  • A simple html page initializing the CreateJS libraries and jQuery;
  • The last release of jQuery;
  • A folder structure containing: assets, core, data, models, scenes, and systems;
  • Core files containing some useful objects for your games;

I will keep these files updated as much as I can.

For those who don’t know, a boilerplate is a “template project” that you can use to start a new work. The template includes files, folders and the structure of the project. If you are happy user of Sublime Text, you can install the Nettuts + Fetch plugin to add this (or other ones) boilerplate automatically.

You can access the repository and propose changes, access:

https://github.com/renatopp/createjs-boilerplate

Read more

CreateJS Logo

CreateJS is a great suite of modular libraries and tools to make HTML5 games and other interactive applications. In the core of CreateJS, there is 4 libraries: EaselJS, SoundJS, PreloadJS, and TweenJS. These libraries are completely independent, i.e., they can be used isolated or even with other game libraries.

EaselJS is the main component of CreateJS. EaselJS controls the game loop, the event manager, the hierarchical organization of objects and the rendering system. It works above the canvas element, thus, providing an easy interface to draw shapes and bitmaps.

SoundJS provides a consistent API to use audio in different browsers. It works via plugins which abstract the actual audio implementation, so playback is possible on any platform without specific knowledge of what mechanisms are necessary to play sounds.

PreloadJS is used to preload all assets to your game, such as images, sounds, data, etc. It provides a complete API with an event system so you can track the loading progress and the connection fails.

TweenJS provides tween function for animations. It can be used independently and provide a simple but complete API to track tweening of object properties and chained commands.

Together with these four libraries, the CreateJS suite also comprises a set of tools to aid the game development process, from applications for exporting SWF animations to EaselJS spritesheets to code completion for editors.

Checkout the video below by the creator of CreateJS to have a better overview of what CreateJS is capable of.

Read more