css制作轨迹
CSS 制作轨迹的方法
使用 CSS 可以创建各种动态轨迹效果,如运动路径、动画轨迹等。以下是几种常见的方法:
使用 @keyframes 和 animation
通过 @keyframes 定义动画关键帧,结合 animation 属性实现元素沿轨迹运动。
.trajectory {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
animation: move 5s linear infinite;
}
@keyframes move {
0% {
left: 0;
top: 0;
}
25% {
left: 100px;
top: 100px;
}
50% {
left: 200px;
top: 50px;
}
100% {
left: 300px;
top: 200px;
}
}
使用 transform 和 translate
通过 transform 属性中的 translate 实现平滑的位移效果。
.trajectory {
width: 50px;
height: 50px;
background-color: blue;
position: absolute;
animation: translate 4s ease-in-out infinite;
}
@keyframes translate {
0% {
transform: translate(0, 0);
}
50% {
transform: translate(200px, 100px);
}
100% {
transform: translate(0, 0);
}
}
使用 motion-path(实验性功能)
CSS 的 motion-path 属性允许元素沿着 SVG 路径运动。
.trajectory {
width: 50px;
height: 50px;
background-color: green;
position: absolute;
offset-path: path("M 0 0 L 100 100 L 200 0");
animation: move-path 3s linear infinite;
}
@keyframes move-path {
0% {
offset-distance: 0%;
}
100% {
offset-distance: 100%;
}
}
使用 transition 和 JavaScript
通过 JavaScript 动态改变元素的位置,结合 CSS transition 实现平滑轨迹效果。
.trajectory {
width: 50px;
height: 50px;
background-color: purple;
position: absolute;
transition: all 1s ease;
}
const element = document.querySelector('.trajectory');
let x = 0;
let y = 0;
setInterval(() => {
x += 10;
y += Math.sin(x / 20) * 10;
element.style.left = `${x}px`;
element.style.top = `${y}px`;
}, 100);
使用 box-shadow 创建轨迹痕迹
通过 box-shadow 记录元素的运动轨迹。

.trajectory {
width: 10px;
height: 10px;
background-color: orange;
border-radius: 50%;
position: absolute;
animation: move-and-trace 5s linear infinite;
box-shadow: 0 0 0 0 transparent;
}
@keyframes move-and-trace {
0% {
left: 0;
top: 0;
box-shadow: 0 0 0 0 transparent;
}
50% {
left: 200px;
top: 100px;
box-shadow: 0 0 10px 5px rgba(255, 165, 0, 0.5);
}
100% {
left: 400px;
top: 0;
box-shadow: 0 0 20px 10px rgba(255, 165, 0, 0);
}
}
以上方法可以根据需求灵活组合,实现更复杂的轨迹效果。






