js实现动画路径
使用CSS动画实现路径动画
通过CSS的@keyframes和transform属性可以定义元素沿路径移动的动画效果。定义一个包含位移、旋转或其他变换的关键帧序列,使元素沿预定路径运动。
@keyframes moveAlongPath {
0% {
transform: translate(0, 0);
}
50% {
transform: translate(200px, 100px);
}
100% {
transform: translate(400px, 0);
}
}
.element {
animation: moveAlongPath 3s linear infinite;
}
使用SVG路径动画
通过SVG的<path>元素和animateMotion标签,可以让元素沿SVG路径运动。定义一个路径后,使用animateMotion指定动画时长和重复方式。
<svg width="500" height="200">
<path id="path" d="M0,100 C100,0 200,200 300,100 S500,100 400,0" fill="none" stroke="gray"/>
<circle r="10" fill="blue">
<animateMotion dur="5s" repeatCount="indefinite">
<mpath xlink:href="#path"/>
</animateMotion>
</circle>
</svg>
使用JavaScript动态计算路径
通过JavaScript动态计算路径上的点,并更新元素位置。结合requestAnimationFrame实现平滑动画。
function animateAlongPath(element, pathPoints, duration) {
const startTime = performance.now();
const totalPoints = pathPoints.length;
function updatePosition(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const pointIndex = Math.floor(progress * (totalPoints - 1));
const { x, y } = pathPoints[pointIndex];
element.style.transform = `translate(${x}px, ${y}px)`;
if (progress < 1) {
requestAnimationFrame(updatePosition);
}
}
requestAnimationFrame(updatePosition);
}
const pathPoints = [
{ x: 0, y: 0 },
{ x: 100, y: 50 },
{ x: 200, y: 100 },
{ x: 300, y: 50 }
];
animateAlongPath(document.getElementById('target'), pathPoints, 3000);
使用GSAP实现复杂路径动画
GSAP(GreenSock Animation Platform)提供了强大的路径动画功能,可以轻松实现复杂路径运动。通过MotionPathPlugin插件定义路径并绑定动画。
gsap.registerPlugin(MotionPathPlugin);
gsap.to("#target", {
duration: 3,
repeat: -1,
motionPath: {
path: "M0,100 C100,0 200,200 300,100 S500,100 400,0",
align: "self",
autoRotate: true
}
});
使用Canvas绘制路径动画
通过Canvas绘制路径并动态更新元素位置。结合requestAnimationFrame实现平滑动画效果。
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const points = [];
let currentIndex = 0;
function generatePath() {
for (let i = 0; i < 100; i++) {
points.push({
x: i * 5,
y: 100 + Math.sin(i * 0.2) * 50
});
}
}
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
for (let i = 1; i < points.length; i++) {
ctx.lineTo(points[i].x, points[i].y);
}
ctx.stroke();
ctx.beginPath();
ctx.arc(points[currentIndex].x, points[currentIndex].y, 10, 0, Math.PI * 2);
ctx.fill();
currentIndex = (currentIndex + 1) % points.length;
requestAnimationFrame(animate);
}
generatePath();
animate();
使用Web Animations API
Web Animations API提供了原生JavaScript动画支持,可以结合路径点计算实现动画效果。

const element = document.getElementById('target');
const pathPoints = [
{ x: 0, y: 0 },
{ x: 100, y: 50 },
{ x: 200, y: 100 }
];
const keyframes = pathPoints.map(point => ({
transform: `translate(${point.x}px, ${point.y}px)`
}));
element.animate(keyframes, {
duration: 2000,
iterations: Infinity
});






