Animation effect using sprite sheets


In this tutorial, we’ll explore how to create an animation effect using sprite sheets, similar to the one on tinkercad

Style

pretty basics style, one thing to keep in mind is the media query. I’m also not following rules such as mobile first.

body {
  background: rgb(200, 200, 202);
}

#sprite-container {
  height: 235px;
  width: 350px;
  background-size: 5250px 235px;
  background-image: url("/micky.png");
}

@media (max-width: 768px) {
  #sprite-container {
    height: 134px;
    width: 200px;
    background-size: 3000px 134px;
  }
}

HTML

The sprite container

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

Javascript

The code for the sprite sheet animation that responds to mouse movement. As the user moves their mouse horizontally across the container, the script calculates which frame of the sprite sheet to display by determining the percentage of the mouse’s position relative to the container’s width. It then moves the background position of the container to show the correct frame. Additionally, at the end we’ve added a resize event to reset the background position (not really needed but hey).

const spriteContainer = document.getElementById('sprite-container');
const frameWidth = spriteContainer.clientWidth;
const totalFrames = 15;

spriteContainer.addEventListener('mousemove', (event) => {
    const persantage = event.offsetX / frameWidth
    const currentFrame = Math.floor(persantage * totalFrames);
    const nextPosition = -currentFrame * frameWidth
    spriteContainer.style.backgroundPosition = `${nextPosition}px 0px`;
});

window.addEventListener("resize", (event) => {
    const frameWidth = spriteContainer.clientWidth;
    spriteContainer.style.backgroundPosition = `${frameWidth}px 0px`;
});