12.12 Animating SVG with CSS
Modern browsers allow you to animate both HTML and SVG elements with CSS. This is a two-stage process.- In the first stage, you select the element you want to animate and set the properties of the animation as a whole.
- In the second stage, you say which properties of the selected element are to change, and at what stages of the animation; these are defined in a
@keyframesspecifier.
Example 1. CSS animation of CSS by using keyframes
<style>
.starStyle{
animation-name: starAnim;
animation-duration: 6s;
animation-iteration-count: 4;
animation-direction: alternate;
animation-timing-function: ease;
animation-play-state: running;
}
@keyframes starAnim {
0% {
fill-opacity: 1.0;
stroke-width: 0;
}
100% {
fill-opacity: 0;
stroke-width: 6;
}
}
</style>
<svg width="400" height="400" viewBox="0 0 200 200"
xmlns="http://www.w3.org/2000/svg">
<use href="grids.svg#grid_200x200"/>
<!-- star Defs -->
<defs>
<g id="starDef">
<path d="M 38.042 -12.361 9.405 -12.944 -0.000 -40.000
-9.405 -12.944 -38.042 -12.361 -15.217 4.944
-23.511 32.361 0.000 16.000 23.511 32.361 15.217 4.944 Z"/>
</g>
</defs>
<use id="star"
href="#starDef"
class="starStyle"
transform="translate(100,100)"
style="fill:#2c5f2d4d; stroke:#2c5f2d;stroke-width:0.5" />
<!-- #2c5f2d -->
</svg>