Monday 22 December 2014

Using CreateJS - EaselJS

In this tutorial we will be exploring the CreateJS suite of libraries. CreateJS is suite of JavaScript libraries and tools for building rich, interactive experiences with HTML5. The CreateJS suite is divided into four libraries.
  • EaselJS - Makes working with HTML5 canvas easy.
  • TweenJS - For tweening HTML5 and JavaScript properties
  • SoundJS - Lets you easily work with HTML5 audio
  • PreloadJS - Lets you manage and coordinate loading of assets
The first library we will look at is EaselJs. Lets get started!
EaselJS is a library for working with the HTML5 canvas. It consists of a full, hierarchical display list, a core interaction model, and helper classes to make working with Canvas much easier. Getting up and running with EaselJS could not be easier. You'll need to define a canvas element in your HTML and reference it in your JavaScript. EaselJS uses the notion of a Stage which is the top level Container for the display list ( the stage will be your canvas element). Below is an HTML fragment and the corresponding JavaScript needed to setup EaselJS.
To reference the above canvas you would use the following.
EaselJS comes with a Graphics class that exposes an easy to use API for generating vector drawing instructions and drawing them to a specified context. The commands are very similar to the normal HTML5 Canvas, while EaselJs adds some of its own new commands as well. If you are not familiar with HTML 5 canvas and the drawing commands, you may want to watch the Canvas Essentials course that was recently released. You will normally not use the Graphics class by itself, but rather access it by the Shape class. Below is a JSFiddle that uses that Shape class to do some drawing.
As you can see in the above code the commands are chainable ShapeObject.graphics.setStrokeStyle(1).beginStroke("rgba(0,0,0,1) etc.. You may also have noticed a call to stage.addChild() within the functions. Anytime you want to put something onto the canvas, you must call stage.addChild(). Within the drawShapes() function, there is a call to stage.update(). To be able to see your changes, you must call stage.update() after each change to the canvas. There is a way to not have to repeatedly call stage.update() and that is by using the Ticker Class. The Ticker provides a centralized tick or heartbeat broadcast at a set interval. Listeners can subscribe to the tick event to be notified when a set time interval has elapsed. Below is how you would use the Ticker class to automatically update the stage.
The Shape class comes with a whole slew of properties you can adjust such as x,y positions, alpha, scaleX,scaleY and quite a few others. Below is a demo showing some of these properties.
Within the drawTheShapes() we generate 15 circles with a line drawn through them, being able to chain the drawing commands makes this dead simple. Then we randomize the shapes position, scale, rotation, and alpha.
You can attach events to the shapes such as click, mousedown/over/out, etc, by using the on() method. In this demo when you click on one of the shapes an alert is thrown up, and on mouseout we log a message to the console. To allow for mouse events on the stage mousedown/over/out etc, you must call stage.enableMouseOver(frequency) where frequency is the number of times per second to broadcast the mouse events. This operation is expensive, so it is disabled by default.
EaselJS ships with a Text class that makes it very easy to create text, and to change properties on that text. You call the constructor passing in the text, a font, and a color i.e. new createjs.Text("Hello World", "20px Arial", "#ff7700") Like the Shape class, it comes with a variety of properties and methods. Below is a demo utilizing the Text class.
Similar to the last demo, we create 25 TextFields, and apply some random values to their properties.
The following demo is a hangman game created using the Shape and Text Class we have discussed so far in this tutorial.
To draw the hangman we use a combination on lineTo(), moveTo(), and for the head we use the arc() method. Within the drawCanvas() function, we call the clear() method on the hangmanShape.graphics which clears out any previous drawings we have done into this shape. We change the TextFields color depending on whether player has won or lost their game.
You can use images by utilizing the Bitmap class. A Bitmap represents an Image, Canvas, or Video in the display list, it can be instantiated using an existing HTML element, or a string (Base64). For example new createjs.Bitmap("imagePath.jpg").
<
Very similar to previous demos we create three bitmaps here, and give some random properties to them.
We are using the Shadow class to create some shadows. The shadow class takes as parameters, the color, offsetX, offsetY, and size of the blur effect etc. myImage.shadow = new createjs.Shadow("#000000", 5, 5, 10). You can apply shadows to any Display Object so this would work for text as well.
A Sprite displays a frame or sequence of frames (like an animation) from a SpriteSheet instance. A sprite sheet is a series of images (usually animation frames) combined into a single image. For example, an animation consisting of eight 100x100 images could be combined into a 400x200 sprite sheet (four frames across by two high). You can display individual frames, play frames as an animation, and even sequence animations together. To initialize a Sprite instance you pass in a SpriteSheet and optional frame number or animation to play, for example, new createjs.Sprite(spriteSheet,"run"). The data passed to the SpriteSheet constructor defines three critical pieces of information:
  • The image or images to use.
  • The positions of individual image frames. This data can be represented in one of two ways: As a regular grid of sequential, equal-sized frames, or as individually defined, variable sized frames arranged in an irregular (non-sequential) fashion.
  • Likewise, animations can be represented in two ways: As a series of sequential frames, defined by a start and end frame [0,3], or as a list of frames [0,1,2,3].
Below is some sample code that would initialize a "character" sprite.
Here is a demo using the Sprite and SpriteSheet Class. You need to click on the stage, and then you can use "A" to move left, and "D" to move right. One thing to note about this demo is that I have Base64 encoded the images and they are included by the "imagestrings.js" external resource. Because we are using a SpriteSheet and interacting with the mouse the canvas gets tainted from cross domain images policy (CORS). By using Base64 strings we can overcome this. If this were hosted on your own domain you would use the Bitmap class as usual by passing a element, or path.
Within the setup() function we are creating the spritesheet. For the "images" key I am passing in characterImage which is a Base64 encoded string. For the "frames" key the character images are 96 pixels high, 75 pixels wide, and there are ten frames(separate images). Below is the image we are using for the spritesheet so you can visualize what it looks like.
Character
For the "animation" key we define a "run" animation that is from "frame" zero to nine. Lastly, we create the character from the spritesheet.
When you move the character left or right we call character.play(). and when you stop moving the character we callcharacter.gotoAndStop(0). Since we only have one "animation" we can just call play() and gotoAndStop() if you had a number of animations you would use a combination of these two plus gotoAndPlay().
The Container Class is a nestable display list that allows you to work with compound display elements. For example you could group arm, leg, torso and head Bitmap instances together into a Person Container, and transform them as a group, while still being able to move the individual parts relative to each other. Children of containers have their transform and alpha properties concatenated with their parent Container. Below is a demo utilizing the Container Class. Click on the stage to move the container by 20 pixels.
Here we are creating three bitmaps and adding them to the container, we are then able to move them all in one go by moving the container, and even though they are in a container you could still move them each individually.
The cache() method of the display object draws the display object into a new canvas, which is then used for subsequent draws. For complex content that does not change frequently (ex. a Container with many children that do not move, or a complex vector Shape), this can provide for much faster rendering because the content does not need to be re-rendered each tick.
The cached display object can be moved, rotated, faded, etc freely, however if its content changes, you must manually update the cache by calling updateCache() or cache() again. You must specify the cache area via the x, y, w, and h parameters. This defines the rectangle that will be rendered and cached using this display object's coordinates. Caching should not normally be used on the Bitmap class as it can degrade performance, however if you want to use a filter on a Bitmap then it must be cached.
Due to size restraints on the JSFiddle embeds I will not be providing a demo for this method, but will link you to a demo on the CreateJs website.
The Filter class is the base class that all filters should inherit from. Filters need to be applied to objects that have been cached using the cache method. If an object changes, you will need to cache it again, or use updateCache(). Note that the filters must be applied before caching. EaselJS comes with a number of pre-built filters. Note that individual filters are not compiled into the minified version of EaselJS. To use them, you must include them manually in the HTML.
  • AlphaMapFilter : Map a greyscale image to the alpha channel of a display object
  • AlphaMaskFilter: Map an image's alpha channel to the alpha channel of a display object
  • BlurFilter: Apply vertical and horizontal blur to a display object
  • ColorFilter: Color transform a display object
  • ColorMatrixFilter: Transform an image using a ColorMatrix
The demo below uses the Color Filter, when you click on the stage it removes the green channel from the image. The Color Filter has the following parameters.
The red,green,blue, and alpha Multipliers are expected to be a number from zero to one, and the red, green, blue, and alpha Offset are expected to be a number from 255 to 255.
We create a regular bitmap object, apply the filter, and the cache the bitmap.
Advertisement
I've created one final demo, that we will build on in the next part of this series, by adding sound, preloading the assets, and using tweens.
In this demo we are utlizing the Bitmap, Text, and Shape, classes to create a Space Invaders type game. I won't be going over every step here since the purpose just to show how to tie the concepts together, but if you have any questions about the code feel free to ask in the comments. The collision detection is provided by osln via Github.
In this tutorial we have taken a look at EaselJS and have made a couple of demo applications. I hope you have found this article helpful and that it gets you excited about using EaselJS. Thanks for reading!

No comments:

Post a Comment