css制作svg动画
使用CSS制作SVG动画
CSS可以用于为SVG元素添加动画效果,包括变换、颜色变化、路径动画等。以下是几种常见的实现方法:
基础SVG结构与CSS动画
在HTML中嵌入SVG,并通过CSS选择器为其添加动画:
<svg width="100" height="100" viewBox="0 0 100 100">
<circle id="circle" cx="50" cy="50" r="40" fill="blue"/>
</svg>
#circle {
animation: pulse 2s infinite;
}
@keyframes pulse {
0% { transform: scale(1); fill: blue; }
50% { transform: scale(1.5); fill: red; }
100% { transform: scale(1); fill: blue; }
}
路径描边动画
通过stroke-dasharray和stroke-dashoffset实现路径绘制效果:
<svg width="200" height="100">
<path id="path" d="M10 50 Q 100 10 190 50"
stroke="black" fill="none" stroke-width="2"/>
</svg>
#path {
stroke-dasharray: 500;
stroke-dashoffset: 500;
animation: draw 3s linear forwards;
}
@keyframes draw {
to { stroke-dashoffset: 0; }
}
变换与过渡效果
使用CSS的transform和transition属性实现平滑过渡:
<svg width="100" height="100">
<rect id="rect" x="10" y="10" width="50" height="50" fill="green"/>
</svg>
#rect {
transition: all 0.5s ease;
}
#rect:hover {
transform: rotate(45deg);
fill: orange;
width: 60px;
}
注意事项
- SVG元素必须内联在HTML中才能应用CSS动画,外部引用的SVG文件无法直接通过CSS控制
- 部分SVG属性(如
d路径数据)无法通过CSS直接修改,需使用JavaScript辅助 - 优先使用
transform而非直接修改尺寸/位置属性以获得更好的性能
高级技巧
组合多个动画效果可以创建更复杂的交互:

#element {
animation:
rotate 3s linear infinite,
colorChange 5s alternate infinite;
}
@keyframes rotate {
to { transform: rotate(360deg); }
}
@keyframes colorChange {
0% { fill: red; }
50% { fill: yellow; }
100% { fill: green; }
}






