From a long time I am posting only about Android. So today I came up with a new interesting tutorial. In this post we will learn JavaScript Sprite Animation. You may have seen JavaScript Sprite Animation many times. All the 2d animations you see in the web most of them are made with JavaScript and HTML5.
We can create really cool animations using JavaScript and HTML5 Canvas. To create our 2D animation we will be using Sprites.  If you are not aware with sprites then don’t worry we will be discussing the things from scratch. So lets begin.
First you can see what will be created at the end of this tutorial. See the below animation clip this is actually what we will be creating.
Now if you liked this animation and want to know how you can also create the same, keep reading 🙂
JavaScript Sprite Animation Video Tutorial
If you are more comfortable in watching a video rather than learning by reading the here is a video explaining this topic as well.
What is Sprite, Spritesheet and Animation?
Sprite
I told you we will be learning JavaScript Sprite Animation. So the first thing we should now that What is a Sprite? Sprite is a normal 2d bitmap image that is considered as a single frame of our animation.
Sprite Sheet
When we club many sprites into a single bitmap we get an spritesheet. So for creating an spritesheet we can use any image editing tools like photoshop, gimp etc. But if you are not good at these just google image search withe the keyword “Spritesheet” and you will get many spritesheets.
Animation
It is basically an illusion we display many image of a sequence rapidly and it feels like it is animating. In this today we will render different sprites to the screens  from our SpriteSheet.
Creating JavaScript Sprite Animation Project
We will not be using any special tool or IDE. I am using Google Chrome and Notepad++. And the main thing we need is a SpriteSheet. So I have the following spritesheet. You can use the same also just save the image to your computer.
As you can see in the above image we have 8 columns and 2 rows. The first row is for right movement and the second row is for left.
When our character is moving rightward then we have to display all the 8 sprites one by one repeatedly. And then it will create an animation. So lets begin.
- Create a folder in your computer I just created SpriteAnimation. Put the above spritesheet inside the folder.
- Now create an HTML file named index.html. And create the basic HTML structure as follows.
1 2 3 4 5 6 7 8 9 10 11 12 |
<!DOCTYPE html> <html> <head> <title>JavaScript Sprite Animation Tutorial</title> </head> <body> </body> </html> |
- Inside body we need an area to render our sprite. For this we will be using HTML5 Canvas. You can easily create a Canvas using the canvas tag.
1 2 3 |
<canvas id='canvas'></canvas> |
- Inside this canvas we will render our sprite. I have given an id to the canvas because we need to access it in our script. Now below the canvas create a script tag to write the JavaScripts.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
<script> //Width and height for our canvas var canvasWidth = 650; var canvasHeight = 350; //the with and height of our spritesheet var spriteWidth = 864; var spriteHeight = 280; //we are having two rows and 8 cols in the current sprite sheet var rows = 2; var cols = 8; //The 0th (first) row is for the right movement var trackRight = 0; //1st (second) row for the left movement (counting the index from 0) var trackLeft = 1; //To get the width of a single sprite we divided the width of sprite with the number of cols //because all the sprites are of equal width and height var width = spriteWidth/cols; //Same for the height we divided the height with number of rows var height = spriteHeight/rows; //Each row contains 8 frame and at start we will display the first frame (assuming the index from 0) var curFrame = 0; //The total frame is 8 var frameCount = 8; //x and y coordinates to render the sprite var x=0; var y=0; //x and y coordinates of the canvas to get the single frame var srcX=0; var srcY=0; //tracking the movement left and write var left = false; //Assuming that at start the character will move right side var right = true; //Speed of the movement var speed = 12; //Getting the canvas var canvas = document.getElementById('canvas'); //setting width and height of the canvas canvas.width = canvasWidth; canvas.height = canvasHeight; //Establishing a context to the canvas var ctx = canvas.getContext("2d"); //Creating an Image object for our character var character = new Image(); //Setting the source to the image file character.src = "character.png"; |
- Now we will create a function to update the frame index. As you can see a variable named curFrame which is initialized with 0. We have to update it each time we will render a the sprite. So create a function named updateFrame().
1 2 3 4 5 6 7 8 9 |
function updateFrame(){ //Updating the frame index curFrame = ++curFrame % frameCount; //Calculating the x coordinate for spritesheet srcX = curFrame * width; } |
- Now finally we will create the function to render the sprite. We render the image using drawImage() method with the context that has been established for the canvas.
1 2 3 4 5 6 7 8 |
function draw(){ //Updating the frame updateFrame(); //Drawing the image ctx.drawImage(character,srcX,srcY,width,height,x,y,width,height); } |
- We need to call the draw function repeatedly to continue rendering the sprites on the canvas. This can be done easily by using setInterval method.
1 2 3 |
setInterval(draw,100); |
- First parameter is the function name (draw), and second parameter is the interval to call the function. So the above statement will call the draw function after every 100ms.
- If you open the your file in browser now you will see something like this.
- As you can see we have to clear the already drawn sprite before rendering the new sprite. For this we will use the clearRect() method.
- Just put this line inside the updateFrame() function.
1 2 3 |
ctx.clearRect(x,y,width,height); |
- And you will see the following.
- To add the left and write movement we need to create two move methods. Write the following code.
1 2 3 4 5 6 7 8 9 10 11 |
function moveLeft(){ left = true; right = false; } function moveRight(){ left = false; right = true; } |
- We need to modify the updateFrame() method as follow.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
function updateFrame(){ //Updating the frame index curFrame = ++curFrame % frameCount; //Calculating the x coordinate for spritesheet srcX = curFrame * width; //Clearing the drawn frame ctx.clearRect(x,y,width,height); //if left is true and the character has not reached the left edge if(left && x>0){ //calculate srcY srcY = trackLeft * height; //decreasing the x coordinate x-=speed; } //if the right is true and character has not reached right edge if(right && x<canvasWidth-width){ //calculating y coordinate for spritesheet srcY = trackRight * height; //increasing the x coordinate x+=speed; } } |
- At last we need to create two buttons left and right, to change the movement and inside the onClick attribute we will call the method moveLeft() and moveRight().
1 2 3 4 5 |
<canvas id='canvas'></canvas><br /> <button onclick='moveLeft()'>Left</button> <button onclick='moveRight()'>Right</button> |
- I have added a background to the canvas to make it look more cool. The final code will look like.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
<!DOCTYPE html> <html> <head> <title>JavaScript Sprite Animation Tutorial</title> </head> <body> <canvas id='canvas'></canvas><br /> <button onclick='moveLeft()'>Left</button> <button onclick='moveRight()'>Right</button> <script> var canvasWidth = 650; var canvasHeight = 350; var spriteWidth = 864; var spriteHeight = 280; var rows = 2; var cols = 8; var trackRight = 0; var trackLeft = 1; var width = spriteWidth/cols; var height = spriteHeight/rows; var curFrame = 0; var frameCount = 8; var x=0; var y=200; var srcX; var srcY; var left = false; var right = true; var speed = 12; var canvas = document.getElementById('canvas'); canvas.width = canvasWidth; canvas.height = canvasHeight; var ctx = canvas.getContext("2d"); var character = new Image(); character.src = "character.png"; function updateFrame(){ curFrame = ++curFrame % frameCount; srcX = curFrame * width; ctx.clearRect(x,y,width,height); if(left && x>0){ srcY = trackLeft * height; x-=speed; } if(right && x<canvasWidth-width){ srcY = trackRight * height; x+=speed; } } function draw(){ updateFrame(); ctx.drawImage(character,srcX,srcY,width,height,x,y,width,height); } function moveLeft(){ left = true; right = false; } function moveRight(){ left = false; right = true; } setInterval(draw,100); </script> </body> </html> |
- If you are having trouble you can leave your comments below.
So thats for this JavaScript Sprite Animation Tutorial guys. Feel free to ask if having any confusions or doubts regarding this JavaScript Sprite Animation Tutorial. And support us by sharing my tutorials to your social profiles. Thank You 🙂