SVG Path Morphing: Animate Between Two Shapes
Learn the principles of SVG path morphing. Understand why matching command counts matter and how to prepare paths for smooth CSS or SMIL transitions.
Detailed Explanation
Path Morphing Fundamentals
SVG path morphing animates one path shape into another by interpolating the coordinates of each command. The key constraint: both paths must have the same number and type of commands.
Basic Example: Circle to Square
Circle (4 cubic segments):
M 50,0 C 78,0 100,22 100,50
C 100,78 78,100 50,100
C 22,100 0,78 0,50
C 0,22 22,0 50,0 Z
Square (4 cubic segments, but with control points on the line):
M 50,0 C 50,0 100,0 100,0
C 100,0 100,100 100,100
C 100,100 0,100 0,100
C 0,100 0,0 0,0 Z
Both have exactly 4 C commands plus M and Z, so the browser can interpolate each parameter pair smoothly.
CSS Animation
@keyframes morph {
0% { d: path("M 50,0 C 78,0 100,22 ..."); }
100% { d: path("M 50,0 C 50,0 100,0 ..."); }
}
.morphing-path {
animation: morph 1s ease-in-out infinite alternate;
}
Note: The CSS d property animation is supported in modern browsers (Chrome 89+, Firefox 97+, Safari 17+).
Preparing Paths for Morphing
- Match command counts: Both paths need identical sequences of M, C, L, etc.
- Convert all curves to cubic: Replace Q, T, S, A with equivalent C commands.
- Add extra points: If one path has more segments, subdivide the simpler path to match.
- Normalize winding: Both paths should go clockwise (or both counterclockwise).
SMIL Alternative
For broader browser support, use SVG <animate>:
<path d="M 50,0 C 78,0 ...">
<animate attributeName="d"
values="M 50,0 C 78,0 ...; M 50,0 C 50,0 ..."
dur="1s" repeatCount="indefinite" />
</path>
Libraries
For complex morphing with auto-normalization, consider libraries like Flubber, GSAP MorphSVG, or d3-shape's interpolation functions.
Use Case
Path morphing is used for toggle icon transitions (hamburger to X, play to pause), interactive state changes, loading animations, data visualization transitions, and creative micro-interactions that give UI elements a fluid, organic feel.