Simple Animation

The SVG standard provides support for animating drawings both internally through animation elements and externally through scripts. This section will demonstrate a simple animation using ECMAscript (a standard that JavaScript and JScript are dialects of). Although there are plans for supporting animation in Inkscape, at the moment there is no support. Adding animation requires editing the SVG file with a text editor.

In the following SVG drawing, the blue square oscillates back and forth (in a supporting SVG viewer). The square still changes opacity when the mouse is over it and it still contains a hypertext link.


<?xml version="1.0"?>

<!-- Created with Inkscape (http://www.inkscape.org/) -->
<svg
   xmlns:svg="http://www.w3.org/2000/svg"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   version="1.0"
   width="150"
   height="150"
   onload="Start(evt)"     1
   id="svg11341">
  <defs
     id="defs1343" />
  <style
     id="style1324"
     type="text/css" >
     rect:hover {fill-opacity:1.0;}
  </style>

  <script type="text/ecmascript"><![CDATA[     2

    var time = 0;
    var delta_time = 50;
    var max_time = 1000;
    var dir = 1;

    var the_rect;

    function Start(evt) {     3

      the_rect = evt.target.ownerDocument.getElementById("rect1353");     4
      Oscillate();
    }

    function Oscillate() {
      time = time + dir * delta_time;
      if (time >  max_time)  dir = -1;
      if (time < -max_time)  dir =  1;

      // Calculate x position
      x_pos = (time * 25) / max_time;
      the_rect.setAttribute("transform", "translate(" +x_pos+ ", 0.0 )");5

      // Repeat
      setTimeout("Oscillate()", delta_time)
    }

    window.Oscillate = Oscillate
  ]]></script>     6

  <g
     id="layer1">
    <a
       xlink:href="http://www.w3.org/"
       style="fill-opacity:0.75"
       id="a1445">
      <rect
         width="90"
         height="90"
         x="30"
         y="30"
         style="fill:#0000ff;stroke:#000000;stroke-width:1px"
         id="rect1353" />
   </a>
 </g>
</svg>

  

1

Instruction to call script on loading file.

2

Start of script.

3

Initialize script.

4

Get reference to rectangle object (our square).

5

Set the rectangle's transform attribute.

6

End of script.