HTML:
<!DOCTYPE html> <html> <head> <link type="text/css" rel="stylesheet" href="/index.css"> <script type="text/javascript" src="/index.js"></script> </head> <body> <div class="animation"></div> </body> </html>
JS:
var spritePosition,
imageLeft,
imageTop,
step;
window.onload = function () {
spritePosition = 100;
imageLeft = 0;
imageTop = 0;
step = 10;
window.setInterval (function () {
document.getElementsByClassName('animation')[0].style.backgroundPosition = spritePosition + "px 0px";
spritePosition = spritePosition + 108;
}, 100);
document.getElementsByTagName('html')[0].addEventListener("keydown", function(e){
if (e.keyCode == 38) { //up
imageTop = imageTop - step;
document.getElementsByClassName('animation')[0].style.top = imageTop + "px";
};
if (e.keyCode == 40) { //down
imageTop = imageTop + step;
document.getElementsByClassName('animation')[0].style.top = imageTop + "px";
};
if (e.keyCode == 37) { //left
imageLeft = imageLeft - step;
document.getElementsByClassName('animation')[0].style.left = imageLeft + "px";
};
if (e.keyCode == 39) { //right
imageLeft = imageLeft + step;
document.getElementsByClassName('animation')[0].style.left = imageLeft + "px";
};
}, false);
};
Things to notice in JS code are window.setInterval - with that we have infinite loop, and document.getElementsByTagName('html')[0].addEventListener("keydown", function(e){ - with that we are listening key events, so you can move image around page.
CSS:
.animation {
width: 102px;
height: 120px;
background-image: url("scottpilgrim_multiple.png");
background-position: 0px 0px;
position: absolute;
}
Sprite I have stolen from this web site, and example you can download from here.