theARTboy
where art meets design
Animation using JS and Canvas
Categories: javascript

This small example used Flash to create the animation frames. I used the awesome tool from Keith Peters, SWFSheet to create the sprite sheet for this demo. The bonus of using this tool is that it will show the nested and code driven animations, unlike the built in export options of Flash.

The JavaScript follows a similar thought process to actionScript which makes sense since they are both ECMA script languages.

View the demo

Here is the code:

[javascript]

<html>
<head>
<title>spritesheet anim</title>
<script type="text/javascript">
window.addEventListener("load", init);
window.addEventListener("resize",onResize);
var image = new Image();
var xpos=0;
var ypos=0;
var dx=0;
var dy=0;
var frameSize=100;
var numFrames=15;
var index=0;
var width=500;
var canvas;
var c;
var tree=new Image();

function init(){
//we’re ready for the loop
image.src = "sheetEye.png";
canvas=document.getElementById("can");
c=canvas.getContext("2d");
canvas.width=window.innerWidth-15;
canvas.height=frameSize;
c.drawImage(image, xpos, ypos, frameSize, frameSize, 0, 0, frameSize, frameSize);
tree.src="tree.png";
c.drawImage(tree,0,0,67,81,200,19,67,81);
setInterval(loop, 1000 / 30);
}
function onResize(){
canvas.width=window.innerWidth-15;
}
function loop()
{
c.fillStyle="rgba(50,50,50,0.1)";
c.fillRect(0,0,canvas.width,canvas.height);
c.drawImage(image, xpos, ypos, frameSize, frameSize, dx, dy, frameSize, frameSize);
xpos += frameSize;
index += 1;
dx+=12;
//dy+=10;

if (index >= numFrames)
{
xpos =0;
ypos =0;
index=0;
//dx=0;
dy=0;
} else if (xpos + frameSize > width)
{
xpos =0;
ypos += frameSize;
}
if (dx>canvas.width)
{
dx=0;
}
c.drawImage(tree,0,0,67,81,200,19,67,81);
c.drawImage(tree,0,0,67,81,600,19,67,81);
}
</script>
</head>
<body>
<canvas id="can" width="1000" height="100">
</canvas>
</body>
</html>

[/javascript]

Leave a Reply

You must be logged in to post a comment.