Animating along a path

Where the power of SMIL animation first becomes apparent to many students, is when the realize that objects can be told to follow paths. Given that paths can be fairly complex (owing to the power of Bézier curves), the notion that we may simply draw one these and instruct something to follow it can let the programmer breathe a large sigh of relief.

Now let's play a bit more with the positioning of these ellipses by letting them follow a curve, using the< animateMotion> tag.


animation along a path

<path id="curve" stroke="black" fill="inherit" stroke-width="3" opacity=".75"
d="M 0,200
C 100,200     0, 100, 100,100 C 200,100 100,200 200,200
C 300,200 200, 100, 300,100 C 400,100 300,200 400,200
C 500,200 400, 100, 500,100 C 600,100 500,200 600,200
z"  /> 
<ellipse id="One" cx="0" cy="0" rx="20" ry="10" fill="inherit" opacity=".75" stroke="black" stroke-width="2">
<animateMotion dur="10s" rotate="auto" repeatCount="indefinite">
<mpath xlink:href="#curve"/>
</animateMotion>
</ellipse>
Link to animated example

In the above example, a series of three identical "mounds" (each 200 pixels to the right of the previous one) have been drawn and the path has been closed by the "z" subcommand. First, it is important to point out that the locus of the ellipse has been specified to be "on the curve" by setting its center (cx,cy) = (0, 0).

You will also observe in this example that the ellipse takes its orientation from the curve itself, due to the rotate="auto" attribute. Also, since the distance traversed by the moving ellipse is greater along the mounds than it is along the straight line (didn't Euclid have something to say on this topic?) the return trip will take less time. That the shortest distance between two points is a straight line is perhaps illustrated by this example that takes the above code and passes a linear path through the same extremities of the smooth curve above. Another example that illlustrates what happens when (cx,cy) = (0, 0) is not true can be seen here.

The animateMotion tag allows SVG content to be moved along a given path. If you have done animation in programming or scripting languages you will, perhaps, immediately appreciate the elegance of the declarative solution! The amount of code it saves is commendable.  As Alex Danilo points out "the motion along the path is paced, so the object travels along the path at a uniform speed no matter what the shape of the path is". This would be very hard to do with JavaScript.

Here's an illustration of animating text that lies along a curve --  the underlying mechanism (of animating the startOffset of text already laid out along a textPath) is a bit different but the results are much the same.

Link to text flowing on a curve

As seen below (except in Firefox where the motion loses the curve), we might also have a shape follow a pathway which itself is in the midst of mutation. This topic (changing the shape of a path) is covered in the next section.