17 Animation

17.1 Introduction

The Web is a dynamic medium and that SVG needs to support the ability to change vector graphics over time. SVG documents can be animated in the following ways:

17.2 Animation Example Using the SVG DOM

The following example shows a simple animation:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG June 1999//EN" 
<svg width="4in" height="3in" 
     fit-box-to-viewport="0 0 400 300"
     onload="StartAnimation()" >

      var timer_increment = 50.
      var max_time = 10000
      var text_element
      StartAnimation() {
        text_element = document.getElementById("TextElement");
      ShowAndGrowElement(timevalue) {
        timevalue = timevalue + timer_increment
        if (timevalue > max_time)
          timevalue = timevalue - floor(timevalue/max_time) * max_time

        // Scale the text string gradually until it is 20 times larger
        scalefactor = (timevalue * 20.) / max_time
        text_element.SetAttribute("transform", "scale(" + scalefactor + ")")

        // Make the string more opaque
        opacityfactor = timevalue / max_time
        text_element.getStyle().setProperty("opacity", "opacity:" + opacityfactor, "")

        // Call ShowAndGrowElement again <timer_increment> milliseconds later.
        setTimeout("ShowAndGrowElement(" + timer_increment + ")")

  <g transform="translate(50,300)" style="fill:red; font-size:10">
    <text id="TextElement">SVG</text>

Download this example

The above SVG file contains a single graphics element, a text string that says "SVG". The animation loops continuously. The text string starts out small and transparent and grows to be large and opaque. Here is an explanation of how this example works: