Animation How to - Create CSS sprite sheet animation by using background image








Question

We would like to know how to create CSS sprite sheet animation by using background image.

Answer


<!DOCTYPE html>
<html>
<head>
<style type='text/css'>
.hi {<!--   ww w . j av a 2s  .com-->
  width: 50px;
  height: 72px;
  background-image: url("http://s.cdpn.io/79/sprite-steps.png");

}
</style>
<script type='text/javascript'>
window.onload=function(){
document.querySelector('.hi').animate([
    {
        backgroundPosition: "0px"
    },
    {
        backgroundPosition: "-500px"
    }
], {
    duration: 800,
    iterations: Infinity,
    easing: 'steps(10)'
});
}
</script>
</head>
<body>
  <img src="http://s.cdpn.io/79/sprite-steps.png" />
  <div class="hi"></div>
</body>
</html>

The code above is rendered as follows: