Select Page

Animate spritesheet using Javascript

A sprite sheet is an image file containing several images or sprites. Combining the small images in one big image file not only improves the game performance but also reduces the memory usage and speeds up the startup time of the game.

For this example we will use the following sprite sheet:

Sprite sheet


<div id="sprite-container">
  <div id="sprite-image">


#sprite-image {
  height: 325px;
  width: 184px;
  background: url("")
    0px 0px;

The above CSS code will display first image or sprite from the sprite sheet.
[Note that the height of each sprite is 325px and width is 184px. (Width of each sprite = total width of the sprite sheet / total number of sprites)]

Finally Javascript:

var animationInterval;
var spriteSheet = document.getElementById("sprite-image");
var widthOfSpriteSheet = 1472;
var widthOfEachSprite = 184;

function stopAnimation() {

function startAnimation() {
  var position = widthOfEachSprite; //start position for the image
  const speed = 100; //in millisecond(ms)
  const diff = widthOfEachSprite; //difference between two sprites

  animationInterval = setInterval(() => { = `-${position}px 0px`;

    if (position < widthOfSpriteSheet) {
      position = position + diff;
    } else {
      //increment the position by the width of each sprite each time
      position = widthOfEachSprite;
    //reset the position to show first sprite after the last one
  }, speed);

//Start animation


See the Pen Sprite Animation using JS by Sagar Shrestha (@webisora) on CodePen.

(Copyright Disclaimer: This image is being used for educational purposes only and is taken from here).


Submit a Comment

Your email address will not be published. Required fields are marked *