Advanced SMIL: Shape Morphing
Shape morphing is one of the most powerful and visually impressive features of SVG animation. It allows you to smoothly transition a shape from one form to another by animating its d (data) attribute.
While CSS can handle simple movements and rotations, path data morphing is where SMIL has the edge.
How Morphiing Works
To morph a shape, you use the standard <animate> tag and target the attributeName="d" property. You provide a "from" path and a "to" path (or a list of paths in the values attribute).
The Golden Rule of Morphing
For a browser to smoothly interpolate between two paths, they must have the same structure. Specifically:
- They must have the exact same number of points.
- They should use the same types of path commands in the same order (e.g., both use 4
Lcommands or 2Qcommands).
If the point counts don't match, the browser won't know how to transition between them, and the shape will "snap" or flicker instantly from one state to the next without any smooth motion.
Example: Path Morphing
In the examples below, we demonstrate a transformation from a square to a star, and a functional example of an "eye" blinking by morphing the curves of its path.
Tips for Better Morphing
- Use a Vector Editor: It's much easier to create morph-compatible paths in tools like Inkscape, Adobe Illustrator, or Figma by taking a base shape and moving its points to create the second shape.
- Keep it Simple: The more points a path has, the harder it is to keep track of them. Try to achieve your desired look with the minimum number of anchor points.
- Check Your Commands: Ensure you aren't mixing absolute (uppercase) and relative (lowercase) commands inconsistently if you can help it. Consistent commands (absolute or relative, not both) make it easier to debug paths when a morph doesn't look right.