JS : Creating animation frame in canvas

Using drawImage method we can animate an object in a webpage. For that we need a sprite sheet image of the object i.e the sequence of images.

player
Fig : girl.png (collected fromĀ  http://jefframos.me/Sprite-Sheet)
<!doctype html>;
<head>
<title>Frame Animation<title>
<meta charset="utf-8">
<script src = 'frame.js'></script>
</head>
<body>
<canvas id='mycanvas' width='1000' height="500"></canvas>
</body>
</html>

window.onload = function(){
var canvas = document.getElementById('mycanvas');
var ctx = canvas.getContext('2d');
var img = new Image();
img.src = 'girl.png';
img.onload = function(){
setInterval(frameAnimation,100);
}
var x = 0,
    y = 0,
    frameSizeX = 100,
    frameSizeY = 200,
    numFrames = 7,
    index = 0;
var frameAnimation = function(){
if(index >= numFrames){
x = 0;
y = 0;
index = 0;
}
ctx.clearRect(350,150,frameSizeX,frameSizeY);
ctx.drawImage(img, x , y , frameSizeX , frameSizeY , 350 , 150 , frameSizeX , frameSizeY );
index++;
x += frameSizeX - 4;
}
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s