Safari Reference Library Apple Developer
Search

Animations

You can use animation properties to animate elements as they move, resize, change color and opacity, and undergo other visual changes. You can also animate 2D and 3D visual effects such as rotating, scaling, and translating elements.

To create an animation, you first set animation properties, then you create keyframes, and then apply the animation to some elements. For example, you set the animation’s name, duration, direction, and iteration count. You can also set a timing function that specifies how an animation progresses between keyframes. The timing function defines a Bezier curve—a path that the animation follows between keyframes. You define keyframes using a special keyframes at-rule.

Note: There are actually two types of animations: declared animations and implicit animations. Declared animations, described in this article, are explicitly executed when the animation properties are applied to elements. Implicit animations are called transitions and are triggered when you set a new value for an animatable CSS property. Read ‚ÄúTransitions‚Äù for details on implicit animations.

iPhone OS Note: In iPhone OS, transitions and animations of the -webkit-transform and opacity properties are performance-enhanced.

How Animations Work

Animations are similar to transitions except you have more fine control by specifying keyframes. A keyframe defines the state of an animation at a particular point in time. A sequence of keyframes define the starting, middle, and ending points of an animation. The frames in between these points are computed based on the animation and style properties you set.

Similar to transitions, when applying an animation to an element’s property, the change animates smoothly from the old value to the new value over time. The property values are computed over time. Therefore, if you query the value of a property during an animation, you may get an intermediate value that is the current animated value, not the old or new value. However, unlike transitions, animations do not change property values at the end of the animation.

Similar to transitions, you can control how these intermediate values are computed over time using a timing function, except that the timing function applies to the part of the animation between keyframes. Read “Using Timing Functions” to learn more about timing functions.

You can create unique effects combining animations with 2D and 3D transforms. For example, Figure 1 shows an animation of elements in 3D space. See the PosterCircle sample code project for the complete source code for this example.

Figure 1  Poster Circle example



Circle Poster example

Setting Animation Properties

Use the CSS animation properties to set basic parameters about an animation. At a minimum, you need to set an animation name and duration. In addition, you can specify how many times an animation iterates, whether it alternates between the begin and end states, and whether the animation should begin in a running or paused state. You can also set a delay before the animation begins.

Each parameter has a corresponding CSS property beginning with -webkit-animation. For example, use the -webkit-animation-name property to specify a name. Use the -webkit-animation-duration property to specify the duration in seconds. Use the -webkit-animation-iteration-count property to specify the number of times the animation repeats. In addition, you can use the -webkit-animation property as a shorthand to set all these parameters in one style rule.

For example, an animation called diagonal-slide is declared in Listing 1. The animation name is diagonal-slide, its duration is five seconds, and it repeats ten times.

Listing 1  Setting animation properties

.diagonalslide {
  -webkit-animation-name: diagonal-slide;
  -webkit-animation-duration: 5s;
  -webkit-animation-iteration-count: 10;
}

The animation name is used to associate it with its keyframes. You use the animation name in the keyframes at-rule as described in “Creating Keyframes.”

Creating Keyframes

Keyframes are specified in CSS using a specialized @-webkit-keyframes at-rule. The keyframes rule consists of the @-webkit-keyframes keyword, followed by the animation name, and then a set of style rules for each keyframe as shown in Listing 2. The style rules are contained in blocks, surrounded by braces, and are preceded by a percentage value marking the keyframe’s point in time. Any style rules can be placed in the blocks including 2D and 3D visual effects.

The value is a percentage of the animation’s duration (or the keywords from or to) . For example, 0% specifies the start of an animation, 50% halfway through an animation, and 100% the end of an animation. The from keyword is equivalent to 0% and the to keyword is equivalent to 100%. When the animation executes, it transitions smoothly from one state to the next in increasing order, from 0% to 100%.

Listing 2 shows a keyframes at-rule where the animation is called wobble and the keyframes move an element back and forth over time. (You set the animation name using the -webkit-animation-name property as described in “Setting Animation Properties.”) In the first keyframe, the value of the element’s left property is 100 pixels. By 40% of the animation duration, the value of the left property animates to 150 pixels. At 60% of the animation duration, the value of the left property animates back to 75 pixels. At the end of the animation, the value of the left property returns to 100 pixels.

Listing 2  Declaring keyframes

    @-webkit-keyframes wobble {
 
      0% {
        left: 100px;
      }
 
      40% {
        left: 150px;
      }
 
      60% {
        left: 75px;
      }
 
      100% {
        left: 100px;
      }
 
    }

Using Timing Functions

Timing functions allow an animation to change speed over its duration. The timing function is a mathematical function that provides a smooth curve or path for the transition. These effects are commonly called easing functions.

You set a timing function in a keyframe block using the -webkit-animation-timing-function property. The timing function determines the speed of an animation from the current to the next keyframe. The timing function is specified using a cubic Bezier curve, which is defined by four control points as illustrated in Figure 3. The first control point is always (0,0) and the last control point is (1,1), so you only need to specify the two in-between control points of the curve. The in-between points are specified as a percentage of the overall duration. For example, this line of code sets the second point to (0.5, 0.2) and the third point to (0.3, 1.0) using the cubic-bezier function:

-webkit-transition-timing-function: cubic-bezier(0.5, 0.2, 0.3, 1.0);

Similar to the -webkit-transition-timing-function property, you can set your control points by passing the cubic-bezier() function as the parameter with your custom control points as arguments or by using constants for common timing effects. For example, Listing 3 shows a keyframes at-rule that uses two timing function constants: ease-out and ease-in. Five keyframes are specified for an animation called bounce. Between the first and second keyframe (the first quarter of the duration) an ease-out timing function is used. Between the second and third keyframe (second quarter of the duration) an ease-in timing function is used. And so on. The effect appears as an element that moves up the page 50 pixels, slowing down as it reaches its highest point then speeding up as it falls back to 100 pixels. The second half of the animation behaves in a similar manner, but only moves the element 25 pixels units up the page creating a bouncing ball effect.

Note: The y-axis increases downwards. Therefore, in the first bounce, when the element‚Äôs y-coordinate changes from 100 to 50 pixels, it moves up by 50 pixels. In the second bounce, when the y-coordinate changes from 100 to 75 pixels, it moves up by 25 pixels, half the height of the first bounce.

Listing 3  Using timing functions in keyframes

    @-webkit-keyframes bounce {
 
      from {
        -webkit-transform: translateY(100px);
        -webkit-animation-timing-function: ease-out;
      }
 
      25% {
        -webkit-transform: translateY(50px);
        -webkit-animation-timing-function: ease-in;
      }
 
      50% {
        -webkit-transform: translateY(100px);
        -webkit-animation-timing-function: ease-out;
      }
 
      75% {
        -webkit-transform: translateY(75px);
        -webkit-animation-timing-function: ease-in;
      }
 
      to {
        -webkit-transform: translateY(100px);
      }
 
    }

Repeating Animations

You use the -webkit-animation-iteration-count property to set the number of times to repeat an animation. Listing 4 defines an animation that slides elements from the upper-left to lower-right corner. The -webkit-animation-iteration-count property is set to 10 causing the animation to repeat 10 times when it is applied.

Listing 4  Creating an animation that repeats

.diagonalslide {
  -webkit-animation-name: diagonal-slide;
  -webkit-animation-duration: 5s;
  -webkit-animation-iteration-count: 10;
}
 
@-webkit-keyframes diagonal-slide {
 
  from {
    left: 0;
    top: 0;
  }
 
  to {
    left: 100px;
    top: 100px;
  }
 
}

Starting Animations

Once you create an animation and specify its keyframes, you apply it to an element to begin the animation. You do this by applying the animation style to an element. This is typically triggered by some event such as the user clicking an element.

Listing 5 shows how to apply an animation to an element when the user clicks it. (The diagonalslide is defined in Listing 4.) When the user taps in the blue box that says “Tap to slide” the onClick attribute changes the style class of the div element to diagonalslide and the animation begins.

Listing 5  Starting an animation

<div onClick="className='diagonalslide'">
    Tap to slide
</div>

The effects of an animation cease once the animation completes or if the animation is removed. You remove an animation by setting the -webkit-animation-name property to a value that does not include the name of that animation.

When an animation finishes running because it has executed the number of times described in its iteration count, the properties that were being animated return to their original values without animation.

To restart an animation, set the -webkit-animation-name property to a value that includes the name of that animation. Because style changes are coalesced, you may have to do this after a short delay. Listing 6 shows how to restart the bounce animation.

Listing 6  Restarting an animation

<style>
top:
.bounce {
  -webkit-animation-name: bounce;
  -webkit-animation-duration: 4s;
  -webkit-animation-iteration-count: 3;
}
</style>
 
<script type="text/javascript" charset="utf-8">
function restartBounce(element)
{
  element.style.webkitAnimationName = '';
  window.setTimeout(function() {
    element.style.webkitAnimationName = 'bounce';
  }, 0);
}
</script>
 
<body>
<div class="bounce" onclick="restartBounce(this)">
</div>
</body>

Handling Animation Events

Several animation-related events are available through the DOM event system. The start and end of an animation, and the end of each iteration of an animation, all generate DOM events. The events are instances of the WebKitAnimationEvent class and the possible types are webkitAnimationStart, webkitAnimationIteration, and webkitAnimationEnd in CSS.

Listing 7 adds an event listener for webkitAnimationEnd events at page load time on the div element with the box identifier. (See Listing 3 for the definition of the bounce keyframes in this sample.) When the webkitAnimationEnd event occurs, an instance of WebKitAnimationEvent is created, the function checks to see if the animation was the bounce animation, and, if so, hides the box by setting the element’s display style to hidden.

Listing 7  Handling animation events

<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no"/>
       <title>Bounce Animation</title>
        <style>
            div#box {
               position: absolute;
               width: 100px;
               height: 100px;
               background-color: blue;
               -webkit-transform: translateY(100px);
            }
            .bounce {
                -webkit-animation-name: bounce;
                -webkit-animation-duration: 4s;
                -webkit-animation-iteration-count: 3;
            }
            @-webkit-keyframes bounce {
                ...
                }
            }
        </style>
        <script type="text/javascript" charset="utf-8">
            function attachEventHandler() {
                box.addEventListener( 'webkitAnimationEnd', function( event ) { alert( "Finished animation!" ); }, false );
            }
        </script>
    </head>
 
<body onload="attachEventHandler()">
    <div id="box" class="bounce">
    </div>
</body>
</html>

Note that an event is generated for each animation-name value and not necessarily for each property being animated since you can animate more than one property of an element at a time. You can animate multiple properties either with a single animation-name value with keyframes containing multiple properties, or with multiple animation-name values. For the purposes of events, each animation-name specifies a single animation.

The time the animation has been running is sent with each event generated. This allows a webkitAnimationIteration event handler to determine the current iteration of a looping animation or the current position of an alternating animation. This time does not include any time the animation was in the paused play state.

Read “Interactive Visual Effects” for how to create interactive user interfaces using visual effects with DOM touch events.

iPhone OS Note: Because the mouse is emulated, events may not behave as you expect on iPhone OS. Read ‚ÄúHandling Events‚Äù for how to make elements clickable.




Last updated: 2010-05-26

Did this document help you? Yes It's good, but... Not helpful...