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:
The following example shows a simple animation:
<?xml version="1.0" standalone="no"?> <!DOCTYPE svg PUBLIC "-//W3C//DTD SVG July 1999//EN" "http://www.w3.org/Graphics/SVG/svg-19990706.dtd"> <svg width="4in" height="3in" fit-box-to-viewport="0 0 400 300" onload="StartAnimation()" > <defs> <script><![CDATA[ var timer_increment = 50. var max_time = 10000 var text_element StartAnimation() { text_element = document.getElementById("TextElement"); ShowAndGrowElement(0); } 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 + ")") } ]]></script> </defs> <g transform="translate(50,300)" style="fill:red; font-size:10"> <text id="TextElement">SVG</text> </g> </svg>
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:
width
and height
attributes indicate that the document should take up
a rectangle of size 4inches by 3inches.
The fit-box-to-viewport
attribute indicates that the initial
coordinate system should have (0,0) at its top left and (400,300) at
its bottom right. (Thus, 1 inch equals 100 user units.)
The onload="StartAnimation()"
attribute indicates that when
the document has been fully loaded and processed, then invoke
ECMAScript function StartAnimation(). StartAnimation()
function is only called once
to give a value to global variable text_element
and to
make the initial call to ShowAndGrowElement()
.
ShowAndGrowElement()
is called every 50 milliseconds and
resets the transform
and style
attributes
on the text element to new values each time it is called.
At the end of ShowAndGrowElement
, the function
tells the ECMAScript engine to call itself
again after 50 more milliseconds.