Getting Down with ...

by ...

Lesson n:

Animation in SVG is the changing of attributes of objects over time. In the last lesson, we covered activating immeadiate effects with the mouse. With animation, we make events happen over a period of time.

Before Starting:

Before we really begin, there are several tags that control animation in SVG.

<set>
A basic animation tag good for changing non-numerical values, such as colors and visibility.
<animate>
All-round animation tag that changes properties over time.
<animateMotion>
Moves object along a path.
<animateTransform>
Transforms object.

Now we can move onto setting up an actual animation tag.

Animation Basics

Let's start off with a simple, red, circle shape.

Now we add some fun, or specifically, an animation tag.

<animate attributeName="cx" from="250" to="750" begin="0s" dur="5s" 
  repeatCount="indefinite" />

This tag goes inside the circle tag, at the end of it. And the result:

As you can see, the center point of the circle, cx, is moving to the right. cx is identified in the attributeName of the <animate> tag. The following from and to define where the variable starts and ends, and the begin and dur define the interval of time for the animation in seconds. The repeatCount can be set to a specific number, or to "indefinite" which means the animation will go on forever. It is in this way that you can animate with all basic circle variables. You can also use multiple animations at the same time, and link the beginning of the animations to the mouse events you learned in the last lesson. See if you can figure out where the mouseover event trigger was placed in the code.

Animation and Rotation on Paths

Animating on object on a path is extremely easy. Using the <animateMotion> tag, define the path as you learned several lessons ago. Then specify the duration, and set rotate to auto.

<rect x="0" y="0" width="25" height="25" fill="blue">
    <animateMotion path="m 150,150 c 20,70 -70,20 -100,-100" dur="10s"
                   rotate="auto" repeatCount="indefinite"/></rect>

Notice how the rectangle rotates in the direction it is moving? Try deleting the rotation definition from the code. Does the rectangle still rotate? Here are some of the possible definitions for rotate:

auto
Automatically rotates object over time in the direction of the motion.
auto-reverse
Automatically rotates object in the opposite direction of the motion.
<x>
Keeps the rotation constant at x degrees, no matter what direction the object is heading.

Okay, you've now got the basics of SVG animation. Together with all of the past lessons, you should have a decent understanding of SVG by now. The following tutorials will be about the applications of SVG.

Exercises: