js实现动画路径
使用 CSS 和 JavaScript 实现动画路径
CSS 的 animation 和 @keyframes 可以结合 JavaScript 动态控制动画路径。通过定义关键帧,元素可以沿着预设路径移动。
@keyframes movePath {
0% { transform: translate(0, 0); }
50% { transform: translate(100px, 50px); }
100% { transform: translate(200px, 0); }
}
.element {
animation: movePath 2s linear infinite;
}
JavaScript 可以动态修改路径或控制动画的启停:
const element = document.querySelector('.element');
element.style.animation = 'movePath 3s ease-in-out infinite';
使用 SVG 和 JavaScript 实现路径动画
SVG 的 <path> 元素结合 getTotalLength() 和 getPointAtLength() 方法可以实现精确路径动画。
<svg width="300" height="200">
<path id="path" d="M10,100 Q150,200 290,100" fill="none" stroke="gray"/>
<circle id="circle" r="10" fill="blue"/>
</svg>
JavaScript 控制元素沿路径移动:
const path = document.getElementById('path');
const circle = document.getElementById('circle');
const pathLength = path.getTotalLength();
let progress = 0;
function animate() {
progress = (progress + 0.005) % 1;
const point = path.getPointAtLength(progress * pathLength);
circle.setAttribute('cx', point.x);
circle.setAttribute('cy', point.y);
requestAnimationFrame(animate);
}
animate();
使用 Canvas 绘制路径动画
Canvas 提供更灵活的路径绘制能力,适合复杂动态路径。
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let position = 0;
function drawPath() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
// 绘制路径
ctx.beginPath();
ctx.moveTo(0, 100);
ctx.quadraticCurveTo(150, 200, 300, 100);
ctx.strokeStyle = 'gray';
ctx.stroke();
// 绘制移动元素
const x = position * 300;
const y = 100 + Math.sin(position * Math.PI) * 100;
ctx.beginPath();
ctx.arc(x, y, 10, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
position = (position + 0.005) % 1;
requestAnimationFrame(drawPath);
}
drawPath();
使用 GSAP 库实现高级路径动画
GSAP 的 MotionPathPlugin 可以简化复杂路径动画的实现。
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.4/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.11.4/MotionPathPlugin.min.js"></script>
<div id="box"></div>
JavaScript 实现:
gsap.registerPlugin(MotionPathPlugin);
gsap.to("#box", {
duration: 3,
repeat: -1,
motionPath: {
path: [
{x: 0, y: 0},
{x: 100, y: 100},
{x: 200, y: 0}
],
curviness: 1.5
},
ease: "power1.inOut"
});
使用 Web Animation API
现代浏览器支持的 Web Animation API 可以直接控制元素运动。
const element = document.getElementById('animated');
const keyframes = [
{ transform: 'translate(0, 0)' },
{ transform: 'translate(100px, 50px)' },
{ transform: 'translate(200px, 0)' }
];
const options = {
duration: 2000,
iterations: Infinity,
direction: 'alternate',
easing: 'ease-in-out'
};
const animation = element.animate(keyframes, options);
animation.play();






