css制作轨迹
使用 CSS 动画和关键帧制作轨迹
通过 @keyframes 和 animation 属性可以创建元素的移动轨迹。定义一个动画路径,让元素沿着设定的路径运动。
.trajectory {
width: 50px;
height: 50px;
background-color: blue;
position: absolute;
animation: move 4s linear infinite;
}
@keyframes move {
0% {
left: 0;
top: 0;
}
25% {
left: 100px;
top: 100px;
}
50% {
left: 200px;
top: 50px;
}
100% {
left: 300px;
top: 200px;
}
}
使用 SVG 和 CSS 结合制作轨迹
通过 SVG 的 path 元素定义轨迹路径,再使用 CSS 的 offset-path 让元素沿路径运动。

<svg width="400" height="200" viewBox="0 0 400 200">
<path id="track" d="M 50,100 C 100,50 150,150 200,100 S 300,50 350,100" fill="none" stroke="gray"/>
</svg>
<div class="object"></div>
.object {
width: 20px;
height: 20px;
background-color: red;
border-radius: 50%;
offset-path: path('M 50,100 C 100,50 150,150 200,100 S 300,50 350,100');
animation: move 3s linear infinite;
}
@keyframes move {
100% {
offset-distance: 100%;
}
}
使用 CSS 过渡和变换制作轨迹
通过 transform 和 transition 实现平滑的轨迹移动效果。适用于简单的直线或曲线路径。

.box {
width: 40px;
height: 40px;
background-color: green;
transition: transform 2s ease-in-out;
}
.box:hover {
transform: translate(200px, 100px) rotate(360deg);
}
使用 CSS 变量和 JavaScript 动态控制轨迹
结合 CSS 变量和 JavaScript 动态计算轨迹坐标,实现更复杂的交互式轨迹。
<div class="dynamic-track"></div>
.dynamic-track {
width: 30px;
height: 30px;
background-color: purple;
position: absolute;
left: calc(var(--x) * 1px);
top: calc(var(--y) * 1px);
}
const element = document.querySelector('.dynamic-track');
let angle = 0;
function updatePosition() {
angle += 0.05;
const x = 100 + Math.cos(angle) * 50;
const y = 100 + Math.sin(angle) * 50;
element.style.setProperty('--x', x);
element.style.setProperty('--y', y);
requestAnimationFrame(updatePosition);
}
updatePosition();
使用 CSS 网格和 Flexbox 制作轨迹
通过网格布局或 Flexbox 结合动画,可以创建元素在网格或弹性容器中的移动轨迹。
.grid-container {
display: grid;
grid-template-columns: repeat(5, 50px);
grid-template-rows: repeat(3, 50px);
gap: 10px;
}
.grid-item {
background-color: orange;
grid-column: 1;
grid-row: 1;
animation: grid-move 5s infinite;
}
@keyframes grid-move {
20% { grid-column: 3; grid-row: 1; }
40% { grid-column: 5; grid-row: 2; }
60% { grid-column: 2; grid-row: 3; }
80% { grid-column: 4; grid-row: 1; }
}






