Sunday 23 February 2014

image animation with html5 tag CANVAS

This time we will learn how to make animation by canvas like this example:

or link below: http://tmtn.vn/html5/monster/
Everytime we press a key, it will open its mouth.
 <canvas> is a tag to display image or video. In this article, we use canvas to display animation image.

In HTML we add a tag canvas:
<title>Rendering states</title>
<canvas id="canvas" width="64" height="64"></canvas>
In script, we create an object monster:
var monster =
{
//The monster's image
image: "monster.png",
//The monster's states
NORMAL: 0,
SCARED: 1,
//Set its initial state
state: 0
}; 
then we load the canvas and draw monster there:
//Set up the canvas and drawing surface
var canvas = document.querySelector("#canvas");
var drawingSurface = canvas.getContext("2d");
//Load the monster's image
var monsterImage = new Image();
monsterImage.addEventListener("load", render, false);
monsterImage.src = monster.image;
 Then, we add event function to change state of monster:
//Change the monster's state by pressing and releasing a key
window.addEventListener("keydown", keydownHandler, false);
window.addEventListener("keyup", keyupHandler, false);
function keydownHandler(event)
{
       //When a key is pressed, change the monster's state to SCARED and render it
       monster.state = monster.SCARED;
      render();
}
function keyupHandler(event)
{
      //When a key is released, change the monster's state to NORMAL and render it
     monster.state = monster.NORMAL;
     render();
}
Finally, we have to draw each state of monster by function render:
function render()
{
     //Render the correct state
     switch(monster.state)
    {
                  case monster.NORMAL:
                  drawingSurface.drawImage
                  (
                             monsterImage,
                              0, 0, 64, 64,
                             0, 0, 64, 64
                  );
                  break;
       case monster.SCARED:
                 drawingSurface.drawImage
                  (
                             monsterImage,
                             64, 0, 64, 64,
                             0, 0, 64, 64
                  );
 }
 We use this image:

No comments:

Post a Comment