js实现动画路径
使用 CSS 和 JavaScript 实现动画路径
通过 CSS animation 结合 @keyframes 可以定义元素沿路径移动的动画。JavaScript 用于动态控制动画的启停或参数调整。
const element = document.getElementById('animated-element');
element.style.animation = 'movePath 3s linear infinite';
// 动态修改路径
function updatePath(newPath) {
const styleSheet = document.styleSheets[0];
styleSheet.insertRule(`
@keyframes movePath {
0% { transform: translate(0, 0); }
100% { transform: translate(${newPath.x}px, ${newPath.y}px); }
}
`, styleSheet.cssRules.length);
}
使用 SVG 和 JavaScript 实现路径动画
SVG 原生支持路径动画,通过 <animateMotion> 标签实现:

<svg width="200" height="200">
<path id="path" d="M10,50 Q50,10 90,50 T130,50" fill="none" stroke="black"/>
<circle r="5" fill="red">
<animateMotion dur="3s" repeatCount="indefinite">
<mpath xlink:href="#path"/>
</animateMotion>
</circle>
</svg>
JavaScript 动态更新路径:
document.getElementById('path').setAttribute('d', 'M10,10 L100,100 Q150,50 200,10');
使用 Canvas 绘制路径动画
通过 Canvas 2D API 逐帧绘制路径动画:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let progress = 0;
function animate() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制路径
ctx.beginPath();
ctx.moveTo(10, 10);
ctx.quadraticCurveTo(100, 100, 200, 50);
ctx.stroke();
// 计算动画点位置
const point = getPointOnQuadraticCurve(10,10, 100,100, 200,50, progress);
ctx.fillRect(point.x - 5, point.y - 5, 10, 10);
progress = (progress + 0.01) % 1;
requestAnimationFrame(animate);
}
function getPointOnQuadraticCurve(x1,y1, x2,y2, x3,y3, t) {
const mt = 1 - t;
return {
x: mt*mt*x1 + 2*mt*t*x2 + t*t*x3,
y: mt*mt*y1 + 2*mt*t*y2 + t*t*y3
};
}
animate();
使用 GSAP 库实现高级路径动画
GSAP 提供强大的路径动画功能:
gsap.to("#logo", {
duration: 5,
motionPath: {
path: "M10,50 Q50,10 90,50 T130,50",
align: "#path",
autoRotate: true
},
repeat: -1,
ease: "power1.inOut"
});
使用 Web Animation API
现代浏览器支持的 Web Animation API 也可实现路径动画:
const element = document.getElementById('fly');
const keyframes = [
{ transform: 'translate(0, 0)' },
{ transform: 'translate(300px, 100px)' }
];
const options = {
duration: 3000,
iterations: Infinity,
easing: 'cubic-bezier(0.42, 0, 0.58, 1)'
};
element.animate(keyframes, options);






