css路径动画制作
css路径动画制作
路径动画可以通过CSS的offset-path属性结合animation实现,定义元素沿指定路径运动的效果。以下是具体实现方法:
定义路径
使用SVG路径或CSS基本形状(如path()、circle())作为运动轨迹。例如:
.path {
offset-path: path('M10,10 L100,100');
}
设置动画
通过offset-distance属性控制元素沿路径移动的距离,结合@keyframes实现动画:
@keyframes move {
0% { offset-distance: 0%; }
100% { offset-distance: 100%; }
}
.element {
animation: move 3s linear infinite;
}
示例代码
完整示例实现一个圆形沿贝塞尔曲线运动:
<style>
.track {
width: 300px;
height: 200px;
border: 1px dashed #ccc;
}
.ball {
width: 20px;
height: 20px;
background: red;
border-radius: 50%;
offset-path: path('M10,80 Q150,0 290,80');
animation: move 2s ease-in-out infinite;
}
@keyframes move {
0% { offset-distance: 0%; }
100% { offset-distance: 100%; }
}
</style>
<div class="track">
<div class="ball"></div>
</div>
兼容性处理
对于不支持offset-path的浏览器,可使用transform模拟路径动画,或引入JavaScript库(如GreenSock)作为降级方案。现代浏览器(Chrome、Firefox、Edge)均支持该特性。

高级技巧
- 结合
rotate: auto让元素自动跟随路径方向旋转 - 使用
calc()动态计算路径关键点 - 通过
animation-timing-function调整运动速率曲线






