用js实现动画
使用 CSS 和 JavaScript 实现动画
通过结合 CSS 的 transition 或 animation 属性与 JavaScript 的事件控制,可以实现平滑的动画效果。CSS 负责动画的视觉效果,JavaScript 负责触发和控制动画。
// 获取元素
const box = document.getElementById('box');
// 添加点击事件触发动画
box.addEventListener('click', () => {
box.style.transition = 'transform 1s ease-in-out';
box.style.transform = 'translateX(100px)';
});
使用 requestAnimationFrame 实现高性能动画
requestAnimationFrame 是浏览器提供的专门用于动画的 API,比 setTimeout 或 setInterval 更适合实现高性能动画。
let start;
const element = document.getElementById('animate');
function step(timestamp) {
if (!start) start = timestamp;
const progress = timestamp - start;
element.style.transform = `translateX(${Math.min(progress / 10, 200)}px)`;
if (progress < 2000) {
window.requestAnimationFrame(step);
}
}
window.requestAnimationFrame(step);
使用 Web Animations API
Web Animations API 是浏览器原生支持的动画 API,可以直接通过 JavaScript 控制复杂的动画序列。
const element = document.getElementById('animate');
element.animate([
{ transform: 'translateX(0)', opacity: 1 },
{ transform: 'translateX(100px)', opacity: 0.5 }
], {
duration: 1000,
iterations: Infinity,
direction: 'alternate',
easing: 'ease-in-out'
});
使用 GSAP 等动画库
GSAP 是一个强大的 JavaScript 动画库,适合实现复杂、高性能的动画效果。
gsap.to("#box", {
duration: 1,
x: 100,
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.fillStyle = 'red';
ctx.fillRect(x, 50, 50, 50);
x += 2;
if (x > canvas.width) x = 0;
requestAnimationFrame(draw);
}
draw();
使用 SVG 动画
SVG 元素可以通过 JavaScript 动态修改属性实现动画效果。

const circle = document.getElementById('circle');
function animate() {
const radius = Math.random() * 50 + 10;
circle.setAttribute('r', radius);
setTimeout(animate, 1000);
}
animate();
每种方法适用于不同的场景,CSS 和 JavaScript 结合适合简单的 UI 动画,requestAnimationFrame 和 Web Animations API 适合复杂交互,GSAP 适合高级动画需求,Canvas 和 SVG 适合图形密集型动画。






