Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

12
 by William Malone Sprite animations can be drawn on HTML5 canvas and animated through JavaScript. Animations are useful in game and interactive application development. Several frames of an animation can be included in a single image and using HTML5 canvas and JavaScript we can draw a single frame at a time. This tutorial will describe how HTML5 sprite animations work. We will go step by step through the process of creating a sprite animation. At the end of the this article we will use the animation we created in a simple HTML5 game. The example code is based off the game development framework: BlocksJS (http://blocksjs.com/). The full game framework with additional features can be downloaded from BlocksJS on GitHub. The source code for the examples in the article is available at the end. Two dimensional frame-based animation can be achieved on HTML5 canvas by rendering an area of a single image on a given interval. The following five frame animation is rendered on a HTML5 canvas at one frame per second (1 fps). Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/ 1 de 12 29/05/2013 12:09

Transcript of Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

Page 1: Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

7/14/2019 Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

http://slidepdf.com/reader/full/create-a-sprite-animation-with-html5-canvas-and-javascript-william-malone 1/12

 by William Malone

Sprite animations can be drawn on HTML5 canvas and animated through JavaScript. Animations are useful in game and interactive application development.

Several frames of an animation can be included in a single image and using HTML5 canvas and JavaScript we can draw a single frame at a time.

This tutorial will describe how HTML5 sprite animations work. We will go step by step through the process of creating a sprite animation. At the end of thethis article we will use the animation we created in a simple HTML5 game.

The example code is based off the game development framework: BlocksJS (http://blocksjs.com/). The full game framework with additional features can be

downloaded from BlocksJS on GitHub. The source code for the examples in the article is available at the end.

Two dimensional frame-based animation can be achieved on HTML5 canvas by rendering an area of a single image on a given interval. The following five

frame animation is rendered on a HTML5 canvas at one frame per second (1 fps).

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/

1 de 12 29/05/2013 12:09

Page 2: Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

7/14/2019 Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

http://slidepdf.com/reader/full/create-a-sprite-animation-with-html5-canvas-and-javascript-william-malone 2/12

Using the dr awI mage method of the canvas context we can change the source position to only draw a cropped portion of one image called a "sprite sheet".

HTML5 canvas animation sprite sheets are fundamentally the same as CSS sprite sheets. A sprite sheet consists of muliple frames in one image. The

following sprite sheet has 10 frames. The width of the image is 460 pixels. Therefore the frame width is 460/ 10 or 46 pixels.

Let's start by loading the sprite sheet image for the coin animation. Create a new I mage object and then set its sr c property to the filename of the image

which will load the image.

var coi nI mage = new I mage( ) ;coi nI mage. sr c = "i mages/ coi n- spr i t e- ani mat i on. png";

 Next we define the sprite object so we can create one (or more later). Invoking the object will simply return an object with three public properties.

f uncti on spr i t e ( opt i ons) {

var t hat = {};

t hat. cont ext = opt i ons. cont ext;t hat. wi dt h = opt i ons. wi dt h;t hat . hei ght = opt i ons. hei ght ;

t hat . i mage = opt i ons. i mage;

r et ur n t hat ;

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/

2 de 12 29/05/2013 12:09

Page 3: Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

7/14/2019 Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

http://slidepdf.com/reader/full/create-a-sprite-animation-with-html5-canvas-and-javascript-william-malone 3/12

}

Grab access to the canvas element using get El ement ByI d and then set its dimensions. We will need the canvas's context to draw to later.

<canvas i d="coi nAni mat i on"></ canvas>

var canvas = document . get El ement ByI d( "coi nAni mat i on") ;canvas. wi dt h = 100;canvas. hei ght = 100;

 Now we can create a sprite object which we will call coi n. Using the opt i ons parameter we set properties of the object which will specify: the context of the

canvas on which the sprite will be drawn, the sprite dimensions, and the sprite sheet image.

var coi n = spr i t e( {cont ext : canvas. get Cont ext ( "2d") ,wi dth: 100,hei ght : 100,i mage: coi nI mage

}) ;

The key to creating sprites from one image is that the context's dr awI mage method allows us to render a cropped section of the source image to the canvas.

context.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh)

i mg Source image object Sprite sheet

sx Source x Frame index times frame width

sy Source y 0sw Source width Frame width

sh Source height Frame height

dx Destination x 0

dy Destination y 0

dw Destination width Frame width

dh Destination height Frame height

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/

3 de 12 29/05/2013 12:09

C t S it A i ti ith HTML5 C d J S i t { Willi M l } htt // illi l / ti l / t ht l5 j i t it i ti /

Page 4: Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

7/14/2019 Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

http://slidepdf.com/reader/full/create-a-sprite-animation-with-html5-canvas-and-javascript-william-malone 4/12

We will use the dr awI mage method in our sprite's r ender method to draw one frame at a time.

Time to draw to the canvas. The spr i te function will need a render method that invokes the dr awI mage method on the canvas' context. The parameters

specify the source image and the bounding rectangle dimensions and position of the source sprite sheet and the destination canvas context.

f uncti on spr i t e ( opt i ons) {

. . .

t hat . r ender = f unct i on ( ) {

/ / Dr aw t he ani mat i ont hat . cont ext . drawImage(

t hat . i mage,0,0,

t hat . wi dt h,t hat . hei ght ,0,

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/

4 de 12 29/05/2013 12:09

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www williammalone com/articles/create html5 canvas javascript sprite animation/

Page 5: Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

7/14/2019 Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

http://slidepdf.com/reader/full/create-a-sprite-animation-with-html5-canvas-and-javascript-william-malone 5/12

0,t hat . wi dt h,t hat . hei ght ) ;

}; . . .

}

Oh, and call the render method.

coi n. r ender ( ) ;

We have drawn the coin, but where is the animation?

We need a method so we can update the position of the sprite sheet's bound rectangle. Let's call it... update. We need also need to keep track of where the

animation is so let's create some properties:

f r ameI ndex

The current frame to be displayed 

t i ckCount

The number updates since the current frame was first displayed 

t i cksPerFr ame

The number updates until the next frame should be displayed 

We could just increment the frame index every time we call the update method, but when running a game at 60 frames per second we might want the

animation to run at a slower fps. Tracking the ticks let's use delay the animation speed. For example we could run the sprite animation at 15 fps by setting the

t i cksPerFr ame to 4 on game loop running at 60 fps.

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/

5 de 12 29/05/2013 12:09

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www williammalone com/articles/create html5 canvas javascript sprite animation/

Page 6: Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

7/14/2019 Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

http://slidepdf.com/reader/full/create-a-sprite-animation-with-html5-canvas-and-javascript-william-malone 6/12

Each time the update method is called, the tick count is incremented. If the tick count reaches the ticks per frame the frame index increments the tick count

resets to zero.

f uncti on spr i t e ( opt i ons) { 

var t hat = {},f r ameI ndex = 0,t i ckCount = 0,t i cksPer Frame = t i cksPer Frame | | 0;

. . .

t hat. updat e = f unct i on ( ) {

t i ckCount += 1;

i f ( t i ckCount > t i cksPer Frame) { 

t i ckCount = 0; 

/ / Go to t he next f r amef r ameI ndex += 1;

}

};

. . .

}

The r ender method can now move the bounding rectangle of the source sprite sheet based on the frame index to be displayed by replacing the sprite width

with the frame width: t hat . wi dt h is replaced with t hat . wi dth / number Of Fr ames.

f uncti on spr i t e ( opt i ons) {

. . .

t hat . r ender = f unct i on ( ) {

/ / Dr aw t he ani mat i ont hat . cont ext . dr awI mage(

t hat . i mage,f r ameI ndex * t hat . wi dth / number Of Fr ames,0,t hat . wi dth / number Of Fr ames,

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/

6 de 12 29/05/2013 12:09

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www williammalone com/articles/create-html5-canvas-javascript-sprite-animation/

Page 7: Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

7/14/2019 Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

http://slidepdf.com/reader/full/create-a-sprite-animation-with-html5-canvas-and-javascript-william-malone 7/12

t hat . hei ght ,0,0,t hat . wi dth / number Of Fr ames,t hat . hei ght ) ;

};

. . .

}

This works until the frame index is greater than the number of frames. We need a new property number Of Fr ames and a conditional to ignore out of range

values.

f uncti on spr i t e ( opt i ons) { 

var t hat = {},f r ameI ndex = 0,t i ckCount = 0,t i cksPerFr ame = 0,number Of Fr ames = opt i ons. number Of Fr ames | | 1;

. . .

t hat. updat e = f unct i on ( ) {

t i ckCount += 1;

i f ( t i ckCount > t i cksPer Frame) { 

t i ckCount = 0; 

/ / I f t he cur r ent f r ame i ndex i s i n r angei f ( f r ameI ndex < number Of Fr ames - 1) {

/ / Go to the next f r amef r ameI ndex += 1;

}}

}; . . .

}

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www.williammalone.com/articles/create html5 canvas javascript sprite animation/

7 de 12 29/05/2013 12:09

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/

Page 8: Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

7/14/2019 Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

http://slidepdf.com/reader/full/create-a-sprite-animation-with-html5-canvas-and-javascript-william-malone 8/12

We want our coin to keep spinning after the first go around. We will need a new l oop property and a conditional which resets the frame index and tick count

if the last frame.

f uncti on spr i t e ( opt i ons) {

. . .

t hat . l oop = opt i ons. l oop;

t hat. updat e = f unct i on ( ) {

t i ckCount += 1;

i f ( t i ckCount > t i cksPer Frame) {

 t i ckCount = 0;

 / / I f t he cur r ent f r ame i ndex i s i n r angei f ( f r ameI ndex < number Of Fr ames - 1) {

/ / Go to the next f r amef r ameI ndex += 1;

} el se i f ( t hat . l oop) {f r ameI ndex = 0;

}}

}; . . .

}

But wait! Without a loop the update will only run once. We need to run the update on a loop...

We use r equest Ani mat i onFr ame (See Paul Irish's post (http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/) for a requestAnimationFrame

 polyfill for support in older browsers) to update and render the sprite at the same rate that the browser repaints.

f unct i on gameLoop ( ) {

wi ndow. requestAnimationFrame( gameLoop) ; 

C ea e a Sp e a o w 5 Ca vas a d JavaSc p { W a a o e } p://www.w a a o e.co /a c es/c ea e 5 ca vas javasc p sp e a a o /

8 de 12 29/05/2013 12:09

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/

Page 9: Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

7/14/2019 Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

http://slidepdf.com/reader/full/create-a-sprite-animation-with-html5-canvas-and-javascript-william-malone 9/12

coi n. updat e( ) ;coi n. r ender ( ) ;

}

/ / St ar t t he game l oop as soon as t he spr i t e sheet i s l oadedcoi nI mage. addEvent Li st ener ( " l oad" , gameLoop) ;

Close, but something is not quite right.

The cl earRect method allows us to clear a region of the destination canvas between animation frames.

context.clearRect(x, y, width, height)

x Clear rectangle x position

y Clear rectangle y position

wi dt h Clear rectangle width

hei ght Clear rectangle height

p p { } p j p p

9 de 12 29/05/2013 12:09

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/

Page 10: Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

7/14/2019 Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

http://slidepdf.com/reader/full/create-a-sprite-animation-with-html5-canvas-and-javascript-william-malone 10/12

t hat . r ender = f unct i on ( ) {

/ / Cl ear t he canvascont ext . clearRect( 0, 0, t hat . wi dt h, t hat . hei ght ) ;

/ / Dr aw t he ani mat i ont hat . cont ext . dr awI mage(

t hat . i mage,f r ameI ndex * t hat . wi dth / number Of Fr ames,0,t hat . wi dt h,t hat . hei ght ,0,0,t hat . wi dt h,

t hat . hei ght ) ;};

};

Clearing the canvas between frames gives us our complete sprite animation.

 Now that we have learned how to create a sprite animation on HTML5 canvas we can use the game loop and animation to create a game. Let's keep the game

simple: tap a coin to get points.

To create our game we need to add a couple of event listeners for desktop (mousedown) and mobile (t ouchst ar t ) and then use a simple circle collision

detection to determine if the coin is tapped. If a coin is hit we remove the coin and create a new one resulting in a score based on the coin size. When creating

new coins the size and speed of spin are randomized.

10 de 12 29/05/2013 12:09

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/

Page 11: Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

7/14/2019 Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

http://slidepdf.com/reader/full/create-a-sprite-animation-with-html5-canvas-and-javascript-william-malone 11/12

We are drawing more than one sprite on the canvas now, so instead of clearing the canvas when we render a sprite we need to we need to clear the canvas at

the beginning the game loop. If we didn't we would clear the all the previous sprites.

With these updates we can create our Coin Tap Game; let's give it a try!

0

Sprite Animation Demo / Coin Tap Game

BlocksJS on GitHub (http://github.com/williammalone/BlocksJS/)

Create HTML5 Drawing App (http://www.williammalone.com/articles/create-html5-canvas-javascript-drawing-app)

HTML5 Game Character (http://www.williammalone.com/articles/create-html5-canvas-javascript-game-character)

Maximum iOS Image Size (http://www.williammalone.com/articles/html5-javascript-ios-maximum-image-size)

11 de 12 29/05/2013 12:09

Create a Sprite Animation with HTML5 Canvas and JavaScript { William Malone } http://www.williammalone.com/articles/create-html5-canvas-javascript-sprite-animation/

Page 12: Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

7/14/2019 Create a Sprite Animation With HTML5 Canvas and JavaScript { William Malone }

http://slidepdf.com/reader/full/create-a-sprite-animation-with-html5-canvas-and-javascript-william-malone 12/12

1

This site williammalone.com (http://www.williammalone.com) and its contents copyright (http://creativecommons.org/licenses/by-sa/3.0/) © 2012 William Malone

(http://www.williammalone.com/about/). It is not affiliated with, sponsored by, or endorsed by any entity other than yours truely: William Malone (http://www.williammalone.com

/about/).

12 de 12 29/05/2013 12:09