css制作svg动画
SVG 动画基础
SVG(Scalable Vector Graphics)动画可通过 CSS 的 @keyframes 和动画属性实现,结合 SVG 元素的特性(如路径、填充、描边)创造动态效果。
关键方法
使用 CSS @keyframes 定义动画
通过 @keyframes 定义动画关键帧,控制 SVG 属性的变化(如 fill、stroke、transform):
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes movePath {
0% { transform: translateX(0); }
50% { transform: translateX(50px); }
100% { transform: translateX(0); }
}
应用动画到 SVG 元素
通过 animation 属性将动画绑定到 SVG 元素:
svg circle {
animation: fadeIn 2s ease-in-out infinite;
}
svg path {
animation: movePath 3s linear infinite;
}
控制 SVG 属性动画
直接修改 SVG 原生属性(如 stroke-dasharray 和 stroke-dashoffset)实现路径绘制效果:
@keyframes draw {
to { stroke-dashoffset: 0; }
}
svg path {
stroke-dasharray: 1000;
stroke-dashoffset: 1000;
animation: draw 3s forwards;
}
响应交互事件
通过伪类(如 :hover)触发动画:
svg rect:hover {
animation: pulse 0.5s ease-out;
}
@keyframes pulse {
50% { transform: scale(1.2); }
}
示例代码
完整示例:

<svg width="200" height="200">
<circle cx="100" cy="100" r="50" fill="blue" class="circle-anim"/>
<path d="M20,100 Q100,20 180,100" stroke="red" stroke-width="2" fill="none" class="path-anim"/>
</svg>
<style>
.circle-anim {
animation: fadeIn 2s infinite, pulse 1.5s infinite;
}
.path-anim {
stroke-dasharray: 500;
stroke-dashoffset: 500;
animation: draw 3s forwards;
}
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
@keyframes pulse {
50% { transform: scale(1.1); }
}
@keyframes draw {
to { stroke-dashoffset: 0; }
}
</style>
注意事项
- 性能优化:优先使用
transform和opacity属性,避免频繁触发重绘。 - 浏览器兼容性:部分 SVG 属性(如
stroke-dasharray)需在支持 SVG 的浏览器中使用。 - 动态控制:通过 JavaScript 动态添加/移除 CSS 类实现更复杂的交互逻辑。






