4. Application 2: Using image sprites for animation


          Another way that image sprites can be used is in simple animation. To implement this, you need to read more on CSS Animations. But do not worry! This section will give you a simplified explanation of CSS animation features in the context of image sprites.

          Let’s say that we want to animate the image in Figure 4. It is a frame by frame shot of a girl walking with arms swinging.

Figure 4. A walking girl


  
  1. <head>
  2. <style>
  3.    .sprite {
  4.      background: url('walking.jpg') no-repeat 0 0;
  5.      width: 97px;
  6.      height: 124px;
  7.      animation: varName 1s steps(4) infinite;
  8.    }
  9.    @keyframes varName{
  10.      from{background-position-x:0px;}
  11.      to{background-position-x:-405px;}
  12.    }
  13. </style>
  14. </head>
  15. <body>
  16.     <div class="sprite"></div>
  17. </body>


Code explanation:

Let us focus on this line of code under the .sprite selector:


animation: varName 1s steps(4) infinite;


  • animation – a CSS selector that has four values
  • varName – a variable name to be used later for the definition of animation direction. It can be any string (use variable naming conventions you have learned in programming)
  • 1s – the duration of the whole animation, from beginning to end. A longer duration will lead to a “slower” animation, while a shorter duration will give a faster animation.
  • steps(4) – the number inside the parenthesis is the number of frames that you have in the image sprite. In Figure 4, we have 4 frames.
  • infinite – the number of iterations for the animation. The value infinite means to loop the animation. A numerical value means to loop the animation for that set number of times.


@keyframes varName{
    from{background-position-x:0px;}
     to{background-position-x:-405px;}
}



The second part of the CSS code is the animation rule. Notice the use of varName as a selector.

  • from{background-position-x:0px;} states the beginning of the animation.
  • to{background-position-x:-405px;} states the ending of the animation. -405px means that the animation will move 405 pixels to the right. 405 pixels is the whole width of the image in Figure 4. If you want to animate all the frames in an image sprite, set the value for this property to the width of the whole image (with a negative sign).

          To view the animation for Figure 4, copy-paste the code on a text editor, save it as an HTML file, and open the HTML file in your browser. Feel free to experiment with the animation values to create more effects on the animation.