SVG: Animations

Il est possible d’animer le contenu SVG en utilisant le format SMIL (Synchronized Multimedia Integration Language). SMIL est un langage de la famille XML qui décrit le déroulement temporel et spatial des différents composants intégrés (images, sons, textes, etc).

On peut également utiliser les animations et transformations CSS, ainsi que l’API Web Animations, mais on ne s’intéresse ici qu’à la syntaxe des animations SVG natives.

animate

animateTransform

La balise <animateTransform> permet d’animer un élément en utilisant une transformation, comme la rotation.
Le type de transformation à utiliser est spécifié par l’attribut type.
Les paramètres de cette transformation sont spécifiés par les attributs from et to — qui accepterons différentes valeurs suivant le type de transformation choisie

Type de transformation Valeur from/to
translate x [y] (= prend une ou deux valeurs)
scale x [y]
rotate angle_degre [x y] où x et y est la position du centre de rotation
skewX, skewY angle_degre
<svg with="100" height="100">
  <rect width="20" height="20" x="5" y="5" fill="black">
    <animateTransform
      attributeType="XML"
      attributeName="transform"
      type="rotate"
      from="0 50 50" to="360 50 50"
      dur="7s" repeatCount="indefinite"/>
  </rect>
</svg>

animateMotion

La balise <animateMotion> permet d’animer un élément en suivant un path donné.

<svg with="100" height="100">
  <rect width="10" height="10" x="5" y="5" fill="black">
    <animateMotion
      path="M0,50 C 50,10 50,10 100,50Z"
      dur="3s" repeatCount="indefinite" />
    </animateMotion>
  </rect>
</svg>
</animateMotion>

On peut également utiliser un élément <mpath> à l’intérieur de l’animation pour référencer un path prédéfinit.

<svg with="100" height="100">
  <path id="path" d="M0,50 C 50,10 50,10 100,50Z" stroke="black" fill="none" />
  <rect width="10" height="10" x="0" y="0" fill="black">
    <animateMotion
      dur="3s" repeatCount="indefinite">
      <mpath xlink:href="#path" />
    </animateMotion>
  </rect>
</svg>

set

La balise set ne permet pas de créer des animations à proprement parler (il n’y a pas de transitions), mais de changer la valeur d’un attribut.

Déclenché par l’utilisateur:

<rect x="5" y="5" dur="4s" width="90" height="90" stroke="blue" fill="white">
  <set attributeName="stroke" to="red" 
       begin="mouseover" end="mouseout" />
</rect>
Hover rect

Déclenché par une animation:

<rect x="5" y="5" width="0" height="90" fill="blue">
  <animate attributeName="width" from="0" to="90"
           id="myLoop" begin="0s;myLoop.end" dur="4s"
           repeatCount="3" />
  <set attributeName="fill" to="green" begin="myLoop.begin" />
  <set attributeName="fill" to="gold" begin="myLoop.repeat(1)" />
  <set attributeName="fill" to="red" begin="myLoop.repeat(2)" />
</rect>
3x 4s