The stroke-dashoffset property can be used to create animations for SVG elements, particularly for paths and shapes with strokes. By manipulating this property, you can create effects such as drawing a line or creating a dashed line animation.
Here's how it works:
-
Define Stroke Dasharray: The
stroke-dasharrayproperty defines the pattern of dashes and gaps in the stroke. For example,stroke-dasharray: 5, 5;creates a pattern of dashes that are 5 units long followed by gaps of 5 units. -
Animate Stroke Dashoffset: The
stroke-dashoffsetproperty specifies where the dash pattern starts. By animating this property, you can create the illusion of the stroke being drawn or moving along the path.
Example
Here’s an example of how to animate an SVG circle using stroke-dasharray and stroke-dashoffset:
<svg width="200" height="200">
<circle cx="100" cy="100" r="80" fill="none" stroke="blue" stroke-width="5"
stroke-dasharray="502" stroke-dashoffset="502">
<animate attributeName="stroke-dashoffset" from="502" to="0" dur="2s" fill="freeze" />
</circle>
</svg>
Explanation
- Circle Definition: The circle has a radius of 80 and a stroke that is not filled.
- Stroke Dasharray: The
stroke-dasharrayis set to502, which is the circumference of the circle (calculated as (2 \pi r)). - Stroke Dashoffset: Initially set to
502, which means the entire stroke is offset and not visible. - Animation: The
<animate>element animates thestroke-dashoffsetfrom502to0over2 seconds, creating a drawing effect as the stroke appears.
This technique can be applied to various SVG shapes to create engaging animations.
