1. Technology

How to Write a Simple SVG Animation

Simple SVG Animation Tutorial

By

Animation can be complex, but that doesn't mean you can't write a simple SVG animation to make an image dynamic. Animation creates motion or action in a graphic. When you are first starting out designing your own moving pictures, you want to begin with something easy. For instances, let's look at a simple opacity change animation.

Creating Your Shape

The first step in any SVG document is to draw your picture:

<rect id="myRect" x="100" y="50" width="100" height="50"
style="fill:blue;stroke-width:5;
stroke:black;opacity:1 />

This code creates a very basic rectangle. To add animation, you select one of the five available animate elements. To keep it simple, we will change the opacity of the rectangle:

<animate xlink:href="#myRect" animateType="CSS" animateName="opacity" from="1" to="0" dur="4s" repeatCount="indefinite">
  • animate—tells the parser you are creating an animation
  • xlink:href—creates a target for the animation i.e. the shape with id 'myRect'
  • animateType—look to CSS for the namespace information
  • animateName—the CSS property for the animation
  • from—the starting point of the animation—opacity 1
  • to—the ending pointing for the animation—opacity 0
  • dur—how long it should take to get from 1 to 0 opacity
  • repeatCount—run the animation continuously

You would not necessarily have to use an element ID such as “myRect” to get the animation to work properly. If you list your animate element directly under the shape code, it becomes a child element of the rectangle. Be sure to close the rect tag after the animation code.

<rect x="100" y="50" width="100" height="50"
style="fill:blue;stroke-width:5;
stroke:black;opacity:1>
<animate xlink:href="#myRect" animateType="CSS" animateName="opacity" from="1" to="0" dur="4s" repeatCount="indefinite">
</rect>

©2014 About.com. All rights reserved.