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:
In script, we create an object monster:<title>Rendering states</title><canvas id="canvas" width="64" height="64"></canvas>
var monster =then we load the canvas and draw monster there:
{
//The monster's image
image: "monster.png",
//The monster's states
NORMAL: 0,
SCARED: 1,
//Set its initial state
state: 0
};
//Set up the canvas and drawing surfaceThen, we add event function to change state of monster:
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;
//Change the monster's state by pressing and releasing a keyFinally, we have to draw each state of monster by function render:
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();
}
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