js动画实现
使用 CSS 动画
CSS 动画通过 @keyframes 和 animation 属性实现,适合简单的动画效果。
@keyframes fadeIn {
from { opacity: 0; }
to { opacity: 1; }
}
.element {
animation: fadeIn 2s ease-in-out;
}
使用 JavaScript 原生 API
通过 requestAnimationFrame 实现高性能动画,适合复杂或交互式动画。
function animate() {
element.style.left = `${currentPosition}px`;
currentPosition += 1;
if (currentPosition < 100) {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
使用 Web Animations API
现代浏览器支持的 API,结合了 CSS 和 JavaScript 的优点。
element.animate(
[{ opacity: 0 }, { opacity: 1 }],
{ duration: 1000, easing: 'ease-in' }
);
使用 GSAP 库
GSAP 是专业的动画库,提供丰富的功能和跨浏览器支持。
gsap.to(".element", { x: 100, duration: 1, ease: "power2.out" });
使用 Canvas 动画
通过 Canvas 绘制逐帧动画,适合游戏或复杂图形。
const ctx = canvas.getContext('2d');
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillRect(x, y, 50, 50);
x += 1;
requestAnimationFrame(draw);
}
draw();
使用 SVG 动画
通过 JavaScript 操作 SVG 属性实现动画。
const svgElement = document.getElementById('svg-path');
let length = svgElement.getTotalLength();
svgElement.style.strokeDasharray = length;
svgElement.style.strokeDashoffset = length;
// 动画效果通过修改 strokeDashoffset 实现
性能优化建议
- 优先使用
transform和opacity,避免触发重排。 - 使用
will-change提示浏览器优化。 - 避免频繁的 DOM 操作,使用离线渲染(如 Canvas)。
跨浏览器兼容性
- 旧版浏览器需使用
setTimeout或setInterval作为requestAnimationFrame的降级方案。 - CSS 动画需添加前缀(如
-webkit-)。 - GSAP 或 polyfill 可解决 Web Animations API 兼容性问题。







