I'd like some help with JavaScript. Could anyone provide me with a basic animation code for a single sprite sheet ... If possible the HTML code as well.
I'd like some help with JavaScript. Could anyone provide me with a basic animation code for a single sprite sheet ... If possible the HTML code as well.
Spritesheet is an image that contains within it other images. Much like a film tape of yesteryear that had photographs that when alternated quickly give the effect of animation.
Some spritesheets are just a strip (only one line) with N images, others are more square and have the images divided by several "lines".
An important rule is that all images within the spritesheet must have the same size (height x width).
I took a look at the internet and found this image:
Ifwelookatitweseethatithas10images,5perline,andatotalsizeof900x495pixels.Thismeansthateachimageis180x247.5pixels.
Ithencreateda<div>
withtheimageinside.Igavethedivtheheightoftheimageandalsogaveoverflow:hidden;
soasnottorevealtherestoftheimagethatcomesoutofthatsizewhichisofasingleimage.
ThenIcreatedalogictochangeposition,takingintoaccountthatthereare10images,2linesand5perline.
Anexamplelookslikethis:
var img = document.querySelector('img');
var pos = 0;
var largura = 180;
var altura = 247.5;
function prox() {
pos++;
if (pos == 10) pos = 0;
var linha = Math.floor(pos / 5) * altura;
var coluna = pos % 5 * largura;
img.style.marginTop = -linha + 'px';
img.style.marginLeft = -coluna + 'px';
}
setInterval(prox, 100);
div {
width: 180px;
height: 247.5px;
overflow: hidden;
}
<div><img src="http://img13.deviantart.net/7fc3/i/2012/288/4/7/volt_sprite_sheet_by_kwelfury-d5hx008.png"alt="">
</div>
(jsFiddle: link )
If you want to see a version that reveals what is going on better you can see here: link