实现思路
- 使用 SVG 路径数据:
- 定义一个 SVG 的
<path>
元素,设置其 d
属性为类似 '8' 字形的路径数据。
- 然后在 CSS 中,通过
@keyframes
的 path
关键字(目前部分浏览器支持,如 Chrome 等),将圆形元素沿着该 SVG 路径运动。
- 使用三角函数计算坐标:
- 可以使用正弦和余弦函数来计算 '8' 字形路径上每个点的坐标。'8' 字形路径可以看作是两个相交的圆的组合,通过合适的三角函数表达式来计算每个点的
x
和 y
坐标。然后在 @keyframes
中逐步改变圆形元素的 left
和 top
属性(如果使用绝对定位)或者 transform: translate(x,y)
来实现沿着路径运动。
关键 CSS 代码片段(使用 SVG 路径数据)
/* 假设圆形元素 */
.circle {
width: 50px;
height: 50px;
border - radius: 50%;
background - color: blue;
position: relative;
animation: moveIn8Shape 5s linear infinite;
}
/* 定义动画 */
@keyframes moveIn8Shape {
from {
offset - path: path('M100,100 A50,50 0 1,0 200,100 A50,50 0 1,0 100,100');
}
to {
offset - path: path('M100,100 A50,50 0 1,0 200,100 A50,50 0 1,0 100,100');
}
}
控制动画速度
animation - duration
:通过设置 animation - duration
属性的值来控制动画的总时长。例如,将其设置为 2s
表示动画在 2 秒内完成一个周期,值越小动画速度越快,反之越慢。
animation - timing - function
:可以使用 linear
(匀速)、ease
(默认,慢 - 快 - 慢)、ease - in
(慢开始)、ease - out
(慢结束)、ease - in - out
(慢开始和慢结束)等不同的时间函数来调整动画过程中的速度变化。
确保不同浏览器兼容性
- 前缀:为
@keyframes
和 animation
相关属性添加浏览器前缀,如 -webkit -
(Chrome、Safari)、-moz -
(Firefox)、-ms -
(IE)、-o -
(旧版 Opera)。例如:
.circle {
-webkit - animation: moveIn8Shape 5s linear infinite;
-moz - animation: moveIn8Shape 5s linear infinite;
-ms - animation: moveIn8Shape 5s linear infinite;
-o - animation: moveIn8Shape 5s linear infinite;
animation: moveIn8Shape 5s linear infinite;
}
@ -webkit - keyframes moveIn8Shape {
from {
-webkit - offset - path: path('M100,100 A50,50 0 1,0 200,100 A50,50 0 1,0 100,100');
}
to {
-webkit - offset - path: path('M100,100 A50,50 0 1,0 200,100 A50,50 0 1,0 100,100');
}
}
@ -moz - keyframes moveIn8Shape {
from {
-moz - offset - path: path('M100,100 A50,50 0 1,0 200,100 A50,50 0 1,0 100,100');
}
to {
-moz - offset - path: path('M100,100 A50,50 0 1,0 200,100 A50,50 0 1,0 100,100');
}
}
@ -ms - keyframes moveIn8Shape {
from {
-ms - offset - path: path('M100,100 A50,50 0 1,0 200,100 A50,50 0 1,0 100,100');
}
to {
-ms - offset - path: path('M100,100 A50,50 0 1,0 200,100 A50,50 0 1,0 100,100');
}
}
@ -o - keyframes moveIn8Shape {
from {
-o - offset - path: path('M100,100 A50,50 0 1,0 200,100 A50,50 0 1,0 100,100');
}
to {
-o - offset - path: path('M100,100 A50,50 0 1,0 200,100 A50,50 0 1,0 100,100');
}
}
@keyframes moveIn8Shape {
from {
offset - path: path('M100,100 A50,50 0 1,0 200,100 A50,50 0 1,0 100,100');
}
to {
offset - path: path('M100,100 A50,50 0 1,0 200,100 A50,50 0 1,0 100,100');
}
}
- 特性检测:使用 Modernizr 等工具进行特性检测。如果浏览器不支持
offset - path
(用于 SVG 路径动画),可以回退到使用三角函数计算坐标的方法,或者提供一个简化的动画效果。