How to animate Sprite Sheets?

Asked

Viewed 2,305 times

4

I would like a help with Javascript. Someone could provide me a basic animation code from a single Sprite sheet... If possible HTML code too.

1 answer

5


Spritesheet is an image that contains within it other images. Very much like an old film tape that had photographs that when alternating 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 dimension (height x width).

I took a look on the internet and found this image:

inserir a descrição da imagem aqui

If we look at it we see that it has 10 images, 5 per line, and total dimension of 900 x 495 pixels. This means that each image has 180 x 247.5 pixels.

I then created a <div> with the image inside. I gave to div the height of the image and also gave overflow: hidden; not to reveal the rest of the image that comes out of that size which is from a single image.

Then I created a logic to change position, taking into account that are 10 images, 2 lines and 5 per line.

An example looks like this:

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: https://jsfiddle.net/szkc2n7b/1/)

If you want to see a version where it reveals what’s going on better you can see here: https://jsfiddle.net/szkc2n7b/

  • 1

    Thank you!! was exactly what I was looking for!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.