SVG: animate tag

By Xah Lee. Date: .

Here's a example of SVG animation. Click on the red square.

<svg>
<rect id="s67180" x="0" y="50" width="50" height="50" style="fill:red" />

<animate xlink:href="#s67180"
 attributeName="x"
 from="0"
 to="100"
 dur="2s"
 begin="click"
 fill="freeze" />

</svg>

Use xlink:href to refer to a element you want to animate. Like this:

<animate xlink:href="#id" …>

This element is called the target.

Value Changes by Frame

The from and to changes a value in one direction.

You can can specify a list of values for the animation, by using values and keyTimes, like this:

values="0;50;20;100" keyTimes="0;0.5;0.9;1"

The values and keyTimes are paired to create key frames for the animation. Like this pair:

valueskeyTimes
00
500.5
200.9
1001

This means:

Change the value from 0 to 50 to 20 to 100. The time it takes to change from one value to another is the keyTimes list.

Here's a example. Click on it.

<svg>
<rect id="r89114" x="0" y="50" width="50" height="50" style="fill:blue" />

<animate xlink:href="#r89114"
 attributeName="x"
 dur="2s"
 values="0;50;20;100"
 keyTimes="0;0.5;0.9;1"
 begin="click"
 fill="freeze" />

</svg>

values overrides from, to, by.

if keyTimes is omitted, it is assumed to be a list from 0 to 1, evenly divided.

Pace of Animation, calcMode

calcMode controls the pace of animation.

Possible values are

<svg>
<rect id="r49857" x="0" y="50" width="50" height="50" style="fill:green" />

<animate xlink:href="#r49857"
 attributeName="x"
 dur="2s"
 values="0;50;20;100"
 keyTimes="0;0.5;0.9;1"
 begin="click"
 calcMode="discrete"
 fill="freeze" />

</svg>

Reference

Animation – SVG 1.1 (Second Edition)

SVG tutorial

  1. SVG Basics
  2. Path
  3. Path Elliptical Arc
  4. Circle Arc
  5. Specifying Styles
  6. Shape Styles
  7. Viewport
  8. viewBox
  9. ViewBox Unit Size
  10. Coordinate Transformation
  11. Text Element
  12. Font Size
  13. Structure Elements
  14. Scripting SVG
  15. SVG Clock
  16. Animation

Canvas Intro

  1. Canvas vs SVG
  2. Canvas intro
  3. Demo: Halma
  4. Demo: Raycaster
Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS in Depth
  4. JS Object Ref
  5. DOM Scripting
  6. SVG
  7. Blog