SVG Animation Techniques: From Simple Strokes to Complex Paths
SVG animation can be simple or detailed. Here are the techniques I use, from stroke drawing to morphing paths, with the gotchas I have hit. SVG is my favorite format for animation on the web. It is resolution independent, styleable with CSS, and capable of effects that are difficult or impossible with other formats. Over years of animating SVGs, I have settled on a set of techniques that cover most of what I need, from simple icon interactions to complex illustrations. Here are those techniques and the gotchas I have hit along the way. Stroke Drawing With stroke-dasharray The most recognizable SVG animation is the drawing effect, where a line appears to draw itself on screen. The technique uses stroke-dasharray to create a dash pattern and stroke-dashoffset to control where the dash starts. By animating the offset from the full path length to zero, the line draws in. .path { stroke-dasharray: 1000; stroke-dashoffset: 1000; animation: draw 2s ease-out forwards; } @keyframes draw { to { stroke-dashoffset: 0; } } The trick is knowing the path length. The getTotalLength method in JavaScript returns it exactly, but I prefer a CSS only approach using a large dasharray value that exceeds the path length. More guides are on the Spark Blog.