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

HTML:

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

CSS:

#sprite-image {
  height: 325px;
  width: 184px;
  background: url("https://webisora.com/wp-content/uploads/2018/07/capguy-walk-1472.png")
    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() {
  clearInterval(animationInterval);
}

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(() => {
    spriteSheet.style.backgroundPosition = `-${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
startAnimation();

Demo:

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).

0 Comments

Submit a Comment

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