sarath
sarath

Reputation: 57

CSS Spritesheet animation keeps moving towards the left

I have a spritesheet (9170px x 350px) that has 70 frames of a single character. Here's my code.

@-webkit-keyframes play {
  100% {
    background-position: -9170px;
  }
}
@keyframes play {
  100% {
    background-position: -9170px;
  }
}
.character-one {
  width: 131px;
  height: 350px;
  border: 1px solid #ddd;
  margin-left: 20px;
  background: url('http://i.imgur.com/gK3C2VZ.png') left center;
  -webkit-animation: play 2s steps(70) infinite;
  animation: play 2s steps(70) infinite;
}
<div class="character-one"></div>

When I open it in the browser, I see the character getting animated, but the spritesheet moves from right to left inside the div that's there. What could the reason be? I figured that normally happens when the steps() are fewer than the number of frames, but in my case everything seems to be OK. Could it be that the frames are not evenly spaced?

Here's the link to the JSFiddle

Upvotes: 0

Views: 953

Answers (2)

Harry
Harry

Reputation: 89750

Though your actual sprite-sheet is 9170px wide, the individual sprites within it actually have a margin on either side. This is what is causing the sliding effect.

As per your code, there are 70 steps and the background moves by 9170px (which is 131px for each step). But each 131px of the sprite don't seem to exactly overlap one another. In the below image, we can see how the first 131px of the spritesheet and the last 131px look like (background added just for visual distinction).

enter image description here

Changing the background-position like in the below snippet seems to produce a much better output.

@-webkit-keyframes play {
  100% {
    background-position: -9144px;
  }
}

@keyframes play {
  100% {
    background-position: -9144px;
  }
}

.character-one {
  width: 131px;
  height: 350px;
  border: 1px solid #ddd;
  margin-left: 20px;
  background: url('http://i.imgur.com/gK3C2VZ.png');
  background-position: -28px center;
  -webkit-animation: play 2s steps(70) infinite;
  animation: play 2s steps(70) infinite;
}
<div class="character-one"></div>


In the below sprite-sheet, we can see how there is equal spacing on all sides for each sprite image. It is taken from the Tree House blog on CSS Sprite Sheet Animations.

enter image description here

Upvotes: 3

Narendra Bhavsar
Narendra Bhavsar

Reputation: 1

Sprite images are wrong sliced, distance is vary in all images. Please update sprite images then problem is solved.

Upvotes: 0

Related Questions