The Mijingo Blog

Latest news, updates, free tutorials, and more from Mijingo.

Animating SVG with JavaScript

by Ryan Irelan

Animating SVG with JavaScript is best achieved using a library that has a healthy amount of functionality and broad browser support. For our examples, we will use the Velocity.js JavaScript library.

Velocity is a lightweight library that “re-implements jQuery’s $.animate() for significantly great performance.”

Let’s jump right in and start animating our SVG.

The first thing we want to do is to tell Velocity which object we want manipulate. For our logo example, we’ll hook into it using the class names we assigned to the SVG shapes.

$(".two")
 .delay(500)
 .velocity({ fill: "#333", strokeWidth: 2})
 .velocity({rotateZ: "10deg"})
 .delay(500)
 .velocity({x: "+=20", y: "100%" });

View Intro to SVG: Example 20

In this example we are selecting the shapes (rect in this case) that have the class of two and then manipulating them. We start with a delay, change the fill color of the shape from white to a black, and then rotate the shape 10 degrees. After that we delay another 500ms and then animate the shape from its starting point to 100% (basically, off the canvas) by changing the x and y coordinates of the SVG shape.

Here’s an example with all of the SVG shapes transformed and moved off the viewport or canvas: View Intro to SVG: Example 21

Browser Support

Velocity.js works all the way back to Internet Explorer 8 and Android 2.3 on mobile devices.

Filed Under: SVG