Getting Started With EaselJS: A Flash-Like Interface for the HTML5 Canvas

Getting Started With EaselJS: A Flash-Like Interface for the HTML5 Canvas

Tutorial Details
  • Estimated Completion Time: 1 hour
  • Difficulty: Beginner
  • Platform: HTML5
  • Language: JavaScript
  • Software used: HTML/JavaScript Editor
  • Libraries Used: EaselJS

There’s been some resistance from Flash developers to our new HTML5 content. In this article – aimed at experienced AS3 coders – we’ll look at EaselJS, a JavaScript library that makes working with the HTML5 canvas very similar to working with the Flash display list.

Subsequent Changes to Techniques & Software

Certain aspects of applications or techniques used in this tutorial have changed since it was originally published. This might make it a little difficult to follow along. We'd recommend looking at these more recent tutorials on the same topic:


The HTML5 Scene

The “war” between Flash and HTML5 isn’t news to anyone involved in browser or mobile development and as Michael points out there’s no harm in learning HTML5 even if you know Flash and ActionScript.

HTML5 is a new and evolving technology and there are currently no full-featured tools quite like the Flash IDE covering the whole workflow to create games or applications, but if you’re familiar with Flash Builder or FlashDevelop it shouldn’t be hard to code in any text editor using external files as your assets.

(Editor’s Note: There are plenty of JavaScript and HTML editors, though – take a look at JetBrains WebStorm for a great example.)


Introducing EaselJS, Tween JS and SoundJS

Luckily for us, Grant Skinner has developed a JavaScript library that will make our learning less complicated. In his own words:

The new Canvas element in HTML5 is powerful, but it can be difficult to work with. It has no internal concept of discrete display elements, so you are required to manage updates manually. The Easel Javascript library provides a retained graphics mode for canvas including a full, hierarchical display list, a core interaction model, and helper classes to make working with Canvas much easier.

EaselJS uses a similar syntax to ActionScript; it has a Display List, Stage, Graphics and even Filters, this will make working with the canvas easier for us Flash developers.

Additionally we can complete our easel development with the TweenJS and SoundJS scripts which, as the names suggest, handle animations and sound.


The Display List

The Display List works very similar to ActionScript:

myStage.addChild(myChild);

In this code, the myStage variable is the linked reference of the canvas to the Stage class in EaselJS. More on that in the example at the end of this tutorial.


Mouse Events

The way to add Mouse Events couldn’t be easier:

myChild.onPress = myFunction
myFunction(){console.log('pressed');}

Text

This code adds a Text object and places it in the stage.

var myText = new Text('Activetuts+', 'Bold 15px Helvetica', #FFF);

myText.x = 25;
myText.y = 25;

myStage.addChild(myText);
myStage.update();

Tickers

The Ticker class provides a centralized tick or heartbeat, broadcast at a set interval; the tick() event can be used as a substitute for an AS3 Timer or EnterFrame event.

The following code sets the frame rate to 30 and deines the stage as the listener for the ticks.

Ticker.setFPS(30);
Ticker.addListener(myStage);

Tweens

The Tween class is an external addition to EaselJS which is available by adding the TweenJS script to our document. It works very similarly to tween engines in ActionScript.

Tween.get(myChild).to(x: 150);

Sounds

We can play a sound by adding the SoundJS script to our document and writing the following code:

SoundJS.add('mySound', 'mySound.mp3', 1);

SoundJS.play('mySound');

Hello World!

An introduction to a programming library would not be complete without a hello world example! Follow these steps to create a very simple HTML5 Canvas hello world containing images, mouse events, text and more.


Step 1: HTML Structure

Let’s prepare our HTML document, it is a simple html structure to begin writing our app.

<!DOCTYPE html>
<html>
	<head>
		<title>Hello World</title>
	</head>
	<body>
	</body>
</html>

Step 2: Hide Mobile Highlight

Let’s add a little bit of CSS too: this line will remove the default highlight when you tap on an element using a mobile browser; without this the mobile experience would decrease drastically.

<!DOCTYPE html>
<html>
	<head>
		<title>Hello World</title>
		
		<style>*{-webkit-tap-highlight-color: rgba(0, 0, 0, 0);}</style>
	
	</head>
	<body>
	</body>
</html>

Step 3: JavaScript Libraries

The following code adds the necessary JavaScript libraries for our app to work.

<!DOCTYPE html>
<html>
	<head>
		<title>Hello World</title>
		
		<style>*{-webkit-tap-highlight-color: rgba(0, 0, 0, 0);}</style>

		<script src="easel.js"></script>
		<script src="Tween.js"></script>
		<script src="HelloWorld.js"></script>
	</head>
	<body>
	</body>
</html>

Step 4: Call Main Function

In the next lines we call our constructor, this is the main function that will be created later in our javascript code.

<!DOCTYPE html>
<html>
	<head>
		<title>Hello World</title>
		
		<style>*{-webkit-tap-highlight-color: rgba(0, 0, 0, 0);}</style>

		<script src="easel.js"></script>
		<script src="Tween.js"></script>
		<script src="HelloWorld.js"></script>

	</head>
	<body onload="Main();">
	</body>
</html>

Step 5: Canvas Tag

The Canvas is added in this line, we assign an ID to reference it later and also set its width and height.

<!DOCTYPE html>
<html>
	<head>
		<title>Hello World</title>
		
		<style>*{-webkit-tap-highlight-color: rgba(0, 0, 0, 0);}</style>

		<script src="easel.js"></script>
		<script src="Tween.js"></script>
		<script src="HelloWorld.js"></script>

	</head>
	<body onload="Main();">
		<canvas id="HelloWorld" width="480" height="320"></canvas>
	</body>
</html>

Step 6: JavaScript

Let’s begin our app creation!

Open your preferred JavaScript editor (a basic text editor will work, but you won’t have syntax highlighting) and prepare to write your awesome app. Remember to save the file with a js extension in your project folder.


Step 7: Define Canvas

We’ll start by defining all the graphic and logic variables.

The next variables represent the HTML canvas element and the stage that will be linked to it. The stage variable will behave in a similar way to the AS3 stage.

/* Define Canvas */

var canvas;
var stage;

Step 8: Background

This variable stores the background image.

/* Background */

var bgSrc = new Image(); //this will store the image data of the source png
var bg; // the bitmap object using easeljs

Step 9: Button

Another variable to store the button image.

/* Button */

var btnSrc = new Image();
var btn;

Step 10: Variables

These are the variables we’ll use, read the comments in the code to know more about them:

/* Variables */

var centerX = 275; //center of stage
var centerY = 150;
var gfxLoaded = 0; //will serve as preloader flag

Step 11: Constructor

The constructor is a function that runs when an object is created from a class; this particular function will be the first to execute when the web page is loaded.

function Main()
{
	//code...
}

Step 12: Link Canvas

This code gets the HTML canvas ID and links it to the EaselJS Stage class. This will make the stage variable behave like the Stage class in AS3.

/* Link Canvas */
	
canvas = document.getElementById('HelloWorld');
stage = new Stage(canvas);


Step 13: Enable Mouse Events

Mouse Events are disabled by default in EaselJS to improve performance. Since we need those in the application, we’ll add the following line:

stage.mouseEventsEnabled = true;

Step 14: Load Graphics

This code is used to preload the graphics with the help of a function that we’ll write later. It sets the Image object we created before to the source png file in our document folder. A name is given to detect which image is loaded and lastly the function that handles the loaded images is called.

/* Load GFX */

 bgSrc.src = 'bg.png';
 bgSrc.name = 'bg';
 bgSrc.onload = loadGfx;
 
 btnSrc.src = 'button.png';
 btnSrc.name = 'button';
 btnSrc.onload = loadGfx;

You’ll need to download the images from above (or make your own) in order for this to work.


Step 15: Set Ticker

The following code sets the frame rate to 30 and defines the stage as the listener for the ticks.

The TweenJS class will listen to this tick to perform the animations.

/* Ticker */

Ticker.setFPS(30);
Ticker.addListener(stage);

Step 16: Preload Graphics

Every time a graphic is loaded this function will run. It will assign each image to a bitmap object and check that all the elements are loaded before proceeding.

function loadGfx(e)
{
	if(e.target.name = 'bg'){bg = new Bitmap(bgSrc);}
	if(e.target.name = 'button'){btn = new Bitmap(btnSrc);}
	
	gfxLoaded++;
	
	/* Display graphics until all of them are loaded */
	
	if(gfxLoaded == 2)
	{
		buildInterface();
	}
}

Step 17: Build Interface

This code places the graphics on the stage and adds a mouse listener to the button.

function buildInterface()
{
	btn.x = centerX - 40;
	btn.y = centerY - 12;
	
	stage.addChild(bg, btn);
	stage.update(); // Very Important
	
	/* Add button listener */
	
	btn.onPress = showText;
}

Step 18: Show Text

The function that will run when the button is pressed, explained in the code commentary.

function showText()
{
	console.log('This works like trace!');
	
	/* Remove Listener */
	
	btn.onPress = null;
	
	/* Create Text */
	
	var msg = new Text('Hello World!', 'Bold 25px Arial', '#EEE');
	
	msg.x = centerX - 70;
	msg.y = centerY;
	
	stage.addChild(msg);
	msg.alpha = 0;
	
	/* Animation */
	
	Tween.get(btn).to({y:centerY + 50}, 300);
	Tween.get(msg).wait(400).to({alpha:1}, 400);
}

That’s it! Click here to see this simple demo in action.


Conclusion

Congratulations! You just made an HTML5 canvas application compatible with all major browsers, including mobile. Stay tuned for more here on Activetuts+.

I hope you liked this tutorial, thank you for reading!

  • emrah

    Bad Javascript looks a bit good now. Looks like as1.

  • Madhu Rakhal Magar

    Great Article and many many thanks to Carlos Yanez the writer of Article and Grant Skinner creator of
    these JavaScript Libraries.

    As a AS3 developer i found very hard to play with HTML5 Canvas hope this JS Libraries will help me to be comfortable with these new and emerging technologies.

    At last thank for such wounderful labraries.

  • http://changesdone.com/ Riccardo

    Great Article.
    These libraries (EaselJS, TweenJS and SoundJS) make using HTML5 Canvas much easier and interesting for a Flash Developer.

    • gr8

      Just learn Jquery

  • knalle

    interesting stuff

  • http://hardwareacceleratedreality.com Joseph Clover

    That looks great, might give it a shot!

  • Omiod

    The sound part is missing.

    • http://michaeljameswilliams.com/ Michael James Williams

      Sorry about that. The “Hello World” example was not supposed to include any sound code.

  • David

    First time I hear about this library and I think it’s amazing. Thank you Grant Skinner, awesome job! And thanks Carlos for the tutorial.

    What I like about this library is that it embodies the ideal of “standard”.

  • http://underLabs.ca Joseph

    Thanks for these tutorials…
    Been trying for a while to get into HTML5 through different tutorials (Envato is awesome), as I am sure Flash/Flex developers have the best background & experience to build above standard HTML5 apps.

  • Castiel

    it seems that i cannot see the demo of this tutorial,
    in fact all demo/files tutorials in this site cannot be seen/downloaded.

    i think there is something wrong with your AWS server

    • http://michaeljameswilliams.com/ Michael James Williams

      Hey Castiel, sorry about this. I’m trying to figure out what’s gone wrong.

      When you say you can’t see the demo, what do you mean? Blank page, 404, unresponsive canvas?

      • Castiel

        “Oops! Google Chrome could not find tutsplus.s3.amazonaws.com”

        that is what i got when i try to open the demo,
        in fact this is happening at every tutorials in every envato sites :(

        i wonder if this is only happen to me or this is a browser issue.

  • Vishwas Gagrani

    Where can i get drag and drop ?

  • Jordan

    Nice primer; thanks Carlos Yanez! The only issue I came across was that it doesn’t explicitly state that all the lines where linkages are defined belong in the constructor. Looking at the source rectified this; plus, d’uh, you can’t have a constructor with nothing in it, otherwise, nothing happens, and you shouldn’t set properties outside of a function. Those would go in some kind of init function… a function that calls when create something, or construct it. Oh wait, that’s the constructor! Oy vey, me, haha.

  • Fabian Miranda

    Nice Tutorial!
    I just have a doubt… when I try it in firefox, everything works fine.
    But when I tested in firefox, I get this error:

    “Unable to get image data from canvas because the canvas has been tainted by cross-origin data.
    easel.js:62″

    “Uncaught An error has occured. This is most likely due to security restrictions on reading canvas pixel data with local or cross-domain images.”

    This happens when I clicked the button or the background, someone has an idea what it could be?

    Thanks!

    • johnmorton

      These errors are a result of not serving your HTML file from a server. If you don’t have a live server to work on, just get MAMP or WAMP (or some other local server) on your machine. Those errors will go away.

  • Ze

    To complement Fabien’s information:

    Unable to get image data from canvas because the canvas has been tainted by cross-origin data.
    Uncaught An error has occured. This is most likely due to security restrictions on reading canvas pixel data with local or cross-domain images. easel.js:69
    a._testHit easel.js:69
    a._getObjectsUnderPoint easel.js:77
    a._handleMouseDown easel.js:83
    a._enableMouseEvents

    • http://michaeljameswilliams.com/ Michael James Williams

      Unfortunately this tutorial’s out of date because of recent changes made to EaselJS, but we are working on getting a new one online!

    • johnmorton

      This is a duplicate answer, but you might only be seeing replies to your own question… These security errors are a result of not serving your HTML file from a server. If you don’t have a live server to work on, just get MAMP or WAMP (or some other local server) on your machine. Those errors will go away.

  • http://makzan.tumblr.com/ Makzan

    I guess you need to have image onload listener assigned before assigning the src property. Otherwise, there is a chance that image is loaded immediately before your onload listener assignment. And causing the onload method never get called.

  • Oleg Zinoviev

    With the latest easel-0.5.js all objects like Stage, Bitmap, Text should be initialized like this: new createjs.Stage(canvas) or new createjs.Bitmap(bgSrc) and not just: new Stage(canvas), like in the tutorial. Because then it throws an error in firebug: ReferenceError: Stage is not defined.

    • James Dalby

      Thanks for this. I knew it had to be something simple that I was missing.