Posted on by & filed under Content - Highlights and Reviews, Web Development.

EaselJS is a JavaScript framework that helps you work with HTML5 Canvas. If you have worked with HTML5 Canvas before, you know it is a simple and immediate mode raster graphic. That means you can draw pretty much any shape and pattern on it, but the canvas will not store any information about separate elements on the canvas. It is all just one big grid of pixels. This also means that you can’t apply any sort of mouse events on different elements on the canvas but only on the entire canvas itself.

In this blog entry we will learn how to use EaselJS, and we will learn how to create a simple particle system effect. How will it work? For every frame a new particle (small black circle) is created in the center of the browser window and is pulled toward the bottom of the window to create the illusion of gravity.

Getting started with EaselJS

EaselJS lets you use HTML5 Canvas in a retained mode. That means that you are able to draw separate objects on the canvas and treat them as such. EaselJS keeps track of the different elements, and supplies you with the possibilities to add event listeners such as mouse events onto single objects. Internally it has a tree structure of all the elements. This means that graphic elements can be nested within each other.

Further, EaselJS also manages the actual rendering of the elements onto the canvas which can be quite complicated and a lot of work if you do it by hand.

If you have worked with Flash and ActionScript before, you will have an easy time adapting to EaselJS because its API is loosely bound to the ActionScript API.

OK, now that we have covered the theoretical basis of EaselJS, let’s take a look at the basic HTML setup:

So all we need for this example is a <canvas> to work with and the EaselJS library. You can find it on Github at https://github.com/CreateJS/EaselJS/downloads.

The last <script> tag was left empty. This is where we will write our code. First we will need to define a few global variables which we will use throughout the example:

The stage represents the heart of the EaselJS application. EaselJS works like ActionScript, which has a hierarchy of graphic elements that can be nested within each other. You could compare it to a tree of graphic elements of which the stage is the root.

The time will be used for the calculation of the position of the particles, but more on that later.

The emitter is an object that defines the X and Y coordinates, where the particles are created as well as the size of them. Once this is done, we can start with the setup procedure.

First off we make sure that the canvas takes up the whole window.

As mentioned above, the stage is pretty much the heart of the application. For EaselJS to be able to manage all the drawing of the particles on the Canvas we have to pass it into the constructor of the Stage class.

The other thing that needs to set up is the Ticker. We set the frame rate to 60 and a callback on the global namespace window. This means that we need to define a global function called tick, which will be called preferably at the given frame rate of 60 FPS (frames per second).

Before we get into the main part of the application, the tick method, let’s take a look at a little helper function first. We need a function that creates a particle and adds it to the stage. This function is called createCircle.

This function shows a few classes that come with EaselJS. First the Graphics class: This class lets you define vector based shapes. Let’s not forget that underneath HTML5 Canvas is a pixel based format.

We create a new Graphic. We set the fillStyle to black using the helper method getRGB. After this we draw a circle at the coordinates of (0, 0) with the size we defined in the emitter object on top. Note that the coordinates do not represent where the circle is on the canvas but rather within the graphic itself. The graphic can be passed into a Shape. The Shape is an object that can be added to the stage and has values (x, y) for the position. By adding the shape to the stage the circle will be drawn on the canvas at the specified coordinates.

(Side note: This is the nesting I was talking about before. The shape is within the stage now, and the graphic is within the shape. The coordinates of an element are always relative to the parent element.)

We set the coordinates of the shape to the values defined by the emitter object. Additionally we define an initial speed for both the X- and Y-axis. The time attribute represents how many milliseconds the particle has been on the stage. It will be needed to define the accurate position for every frame of the animation.

With this function ready we can go over the important tick function that will be called every single frame. This function is used to create new particles and recalculates the position of the existing particles.

As a first step we calculate the time difference between the last call of tick and now. This time is represented by elapsed. Also for every new frame we create a new particle. We use our helper function for that.

In the next step we loop over every element, that has been added to the stage and update its position. The stage has a method getNumChildren that tells us the amount of elements on the stage as well as a method getChildAt that returns the element at the given index. The index is a consecutive number that represents the order in which the elements were added to the stage, and therefore also the same order in which the elements are drawn onto the canvas. The order does not really matter in this example. First we update the time that the element has been alive for. Elapsed represents the time in milliseconds, but we store it in seconds on the particle itself.

Now we update the X and Y position. The calculation for the X coordinate is a form of ease-out. That means that the particle moves to the side of the screen faster at first and slower later. The calculation of the Y axis resembles the mathematical representation of the free fall, which is the original position plus the speed multiplied by the time passed since creation plus a constant for the gravity (90) multiplied by time squared. All this juggling with the numbers just lets the particle accelerate towards the bottom of the screen over time.

What is left to do is to take out a particle once it has left the screen. Using a simple if comparison, we can find out if the particle is already below the bottom of the screen. If so, remove it from the stage and reduce the counter of the loop by one, since there is one less particle on the stage now.

At the end we call stage.update(). This updates all the changes on the actual canvas element. Up to this point we only changed values it in the code, but not on the canvas. This function is used, so it updates all the graphics at once, instead of all the particles separately.

Before we are done we need to call setup() on the global scope to get everything started.

Wow, that was a lot to take in, I know. What have we built? All in all it just consists of three simple functions.

  • A setup function: creating the Stage and the Ticker.
  • A tick function: constantly creating new particles and updating their positions.
  • And a helper function: that creates the particle.

If you go over the application you will see a very simple and flat structure. It is always good to go over the code again and take a close look at each of the steps. The more often you review your own code the clearer and more obvious it gets.

Check out the documentation of EaselJS and browse through the API at: http://www.createjs.com/Docs/EaselJS/.

Give EaselJS a shot and create a few nice demos. It is a great tool that makes working with HTML5 Canvas a lot easier.

Safari Books Online has the content you need

Check out these HTML5 books available from Safari Books Online:

HTML5 is the most significant new advancement the web has seen in many years. HTML5 adds many new features including the video, audio, and canvas elements, as well as the integration of SVG. HTML5 Multimedia Development Cookbook is packed full of recipes that will help you harness HTML5’s next generation multimedia features. Whether you’re a seasoned pro or a total newbie, this book gives you the recipes that will serve as your practical guide to creating semantically rich websites and apps using HTML5. Get ready to perform a quantum leap harnessing HTML5 to create powerful, real world applications.
The HTML5 canvas is revolutionizing graphics and visualizations on the Web. Powered by JavaScript, the HTML5 Canvas API enables web developers to create visualizations and animations right in the browser for the first time without Flash. HTML5 Canvas Cookbook covers the fundamental methods and properties of the HTML5 canvas API. As soon as you are familiar with the API, the book provides advanced techniques for handling animations, image and video manipulations, canvas interactivity, data visualizations, game development, 3D modeling, and more.
HTML5 is revolutionizing the way web applications are developed, and HTML Canvas puts you right in the middle the action. You’ll learn how to build interactive multimedia applications with HTML5’s Canvas, using this new element to draw, animate, compose images, and more. You’ll also learn the best way to use existing JavaScript libraries, as well as how to incorporate related aspects such as audio and video.
One of HTML5’s most exciting features, Canvas provides a powerful 2D graphics API that lets you implement everything from word processors to video games. In Core HTML5 Canvas Development, best-selling author David Geary presents a code-fueled, no-nonsense deep dive into that API, covering everything you need to know to implement rich and consistent web applications that run on a wide variety of operating systems and devices.

About this author

Mathias Paumgarten, co-author of HTML5 Games Most Wanted, is a web developer who focuses on front-end and interaction development. Starting with a background in Flash development, he now focuses mainly on JavaScript. He found his passion for the web and code-based animation at a very young age and made his way from a small town in Austria all the way to New York City where he currently works for Firstborn Multimedia as a Creative Developer. Part of his work can be found at https://github.com/MathiasPaumgarten and http://www.mathias-paumgarten.com/.

Tags: EaselJS, html5, HTML5 Canvas, raster graphic,

One Response to “Creating a Particle System with EaselJS”

  1. Gil

    EaseIJS or EaseUS? Too much of a similarity if you ask me. Hopefully you two will play nice now.