js实现动画案例
使用 CSS 和 JavaScript 实现基础动画
通过 JavaScript 动态修改元素的 CSS 属性可以实现平滑的动画效果。例如,移动一个方块从左侧到右侧:
const box = document.getElementById('box');
let position = 0;
function animate() {
position += 2;
box.style.left = position + 'px';
if (position < 300) requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
对应的 HTML 和 CSS:
<div id="box" style="width:50px; height:50px; background:red; position:absolute;"></div>
使用 Web Animation API
现代浏览器支持 Web Animation API,提供更精细的控制:

const element = document.getElementById('animated');
element.animate([
{ transform: 'translateX(0px)', opacity: 1 },
{ transform: 'translateX(300px)', opacity: 0.5 }
], {
duration: 1000,
iterations: Infinity,
direction: 'alternate'
});
使用 GSAP 高级动画库
GSAP(GreenSock Animation Platform)是专业的动画库,适合复杂场景:
gsap.to(".box", {
x: 200,
duration: 1,
rotation: 360,
ease: "bounce.out"
});
Canvas 动画实现
通过 Canvas 绘制逐帧动画:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let x = 0;
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, 50, 50, 50);
x = (x + 2) % canvas.width;
requestAnimationFrame(draw);
}
draw();
SVG 动画示例
结合 JavaScript 操作 SVG 属性:
const circle = document.getElementById('svg-circle');
let radius = 10;
function pulse() {
radius = (radius === 10) ? 20 : 10;
circle.setAttribute('r', radius);
setTimeout(pulse, 500);
}
pulse();
动画性能优化技巧
使用 transform 和 opacity 属性触发硬件加速,避免频繁重排。优先使用 requestAnimationFrame 而非 setTimeout 保证流畅性。复杂动画建议使用 CSS will-change 属性预声明变化。
响应式动画控制
通过事件监听实现交互式动画:
const btn = document.getElementById('toggle');
const box = document.getElementById('animated-box');
btn.addEventListener('click', () => {
box.style.animationPlayState =
box.style.animationPlayState === 'paused' ? 'running' : 'paused';
});






