SVG Line Animation
SVG line animation takes a slightly different approach in animating. The first difference is that instead of animating shapes, you animate the path
element (and sometimes polyline
). The path
element is the SVG equivalent to the pen tool.
SVG line animation is really somewhat of an illustration of drawing a line. This is done by modifying the stroke-dasharray
and stroke-dashoffset
properties. It's best demonstrated by example.
- Animated line drawing in SVG - See interactive demonstration illustrating line animation concept
We set the stroke-dasharray
property to be equal to the total length of the path. We then set the stroke-dashoffset
to be either 0 or the length of the path, depending on the direction we want the drawing to happen in. When we trigger the animation, we'll change the stroke-dashoffset
to the opposite value. We still use the transition property to make it animate.
Here we have a simple line path.
<svg id="ex4" xmlns="http://www.w3.org/2000/svg" viewBox="100 200 1080 240">
<style>
#ex4 path {
fill: none;
stroke: black;
stroke-width: 8px;
}
</style>
<path d="M181,266c6.259324284800016,-144.79776015789997,168.7597092008,201.2022217284,314,44c62.24029079920001,-146.2022217284,184.76732259510004,81.35544128800001,272,-72"/>
</svg>
Now we'll animated it one way.
<svg id="ex5" xmlns="http://www.w3.org/2000/svg" viewBox="100 200 1080 240">
<style>
#ex5 path {
fill: none;
stroke: black;
stroke-width: 8px;
stroke-dasharray: 720;
stroke-dashoffset: 0;
transition: stroke-dashoffset 4s linear;
}
#ex5:hover path {
stroke-dashoffset: 720;
}
</style>
<path d="M181,266c6.259324284800016,-144.79776015789997,168.7597092008,201.2022217284,314,44c62.24029079920001,-146.2022217284,184.76732259510004,81.35544128800001,272,-72"/>
</svg>
And then the other way
<svg id="ex6" xmlns="http://www.w3.org/2000/svg" viewBox="100 200 1080 240">
<style>
#ex6 path {
fill: none;
stroke: black;
stroke-width: 8px;
stroke-dasharray: 720;
stroke-dashoffset: 720;
transition: stroke-dashoffset 4s linear;
}
#ex6:hover path {
stroke-dashoffset: 0;
}
</style>
<path d="M181,266c6.259324284800016,-144.79776015789997,168.7597092008,201.2022217284,314,44c62.24029079920001,-146.2022217284,184.76732259510004,81.35544128800001,272,-72"/>
</svg>
Fancy Example Demos
- Cityscape line animation with lightbulb at the end
- Original complete demonstration by Sara Soueidan
- Simplified version of demonstration
- Explanation of key demonstration parts from Styling And Animating SVGs With CSS
JavaScript Libraries
There are several JavaScript libraries to help you with SVG animation. One easy to use and interesting one for SVG Line animation is Lazy Line Painter. With this library you can drop your SVG graphic into the web page and it will generate most of the code you nee to use for it.
More Resources
- Animated line drawing in SVG - See interactive demonstration illustrating line animation concept
- The State of SVG Animation - Skip the first section about SMIL