Loading

Interactivity and Animation in SVG

 

  • Animation: using <animate> we can animate objects in SVG

Example:

<svg width="500" height="500">
  <circle cx="250" cy="250" r="50" fill="red">
    <animate attributeName="cx" from="50" to="450" dur="5s" repeatCount="indefinite" />
  </circle>
</svg>
  • <animate>: This is the animation element nested inside the circle element. It animates one of the circle's attributes.
  • from="50": The starting value of the cx attribute. The animation starts with the circle's center at x-coordinate 50.
  • to="450": The ending value of the cx attribute. The animation ends with the circle's center at x-coordinate 450.
  • dur="5s": Specifies the duration of the animation, which is 5 seconds.
  • repeatCount="indefinite": Specifies that the animation should repeat indefinitely.

  • Interactivity: provides dynamic user experience.
  • It can be done by many methods here we are going to see about inline eventhandlers

Example:

  <svg width="500" height="500">
    <circle class="circle" cx="250" cy="250" r="50" fill="red"
      onmouseover="this.setAttribute('fill', 'blue');"
      onmouseout="this.setAttribute('fill', 'red');"
      onclick="alert('Circle clicked!')" />
  </svg>

Output: