Hostingheaderbarlogoj
Join InMotion Hosting for $3.49/mo & get a year on Tuts+ FREE (worth $180). Start today.
Advertisement

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

by
Gift

Want a free year on Tuts+ (worth $180)? Start an InMotion Hosting plan for $3.49/mo.

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!

Advertisement