JavaScript 动画效果可以通过多种方式实现,主要涉及以下几个基础概念:
CSS 提供了 @keyframes
规则和 animation
属性来实现动画效果。
/* 定义关键帧 */
@keyframes slideIn {
from {
transform: translateX(-100%);
}
to {
transform: translateX(0);
}
}
/* 应用动画 */
.element {
animation: slideIn 1s ease-in-out;
}
通过 JavaScript 动态修改元素的 CSS 属性来实现动画。
const element = document.querySelector('.element');
let start = null;
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);
如 GSAP(GreenSock Animation Platform),提供了更强大和灵活的动画控制。
import { gsap } from 'gsap';
gsap.to('.element', { duration: 1, x: 200, ease: 'power2.inOut' });
requestAnimationFrame
可以确保动画在浏览器重绘之前执行,避免掉帧。requestAnimationFrame
替代 setTimeout
或 setInterval
。transform: translateZ(0)
)提升渲染性能。通过以上方法,可以有效地创建和控制 JavaScript 动画效果,提升用户体验。
领取专属 10元无门槛券
手把手带您无忧上云