流畅且高性能的动画在现代 Web 应用程序中至关重要。然而,管理不当可能会使浏览器的主线程过载,导致性能不佳和动画卡顿。 requestAnimationFrame (rAF) 是一种浏览器 API,旨在将动画与显示器的刷新率同步,从而确保与 setTimeout 等替代方案相比更流畅的运动。但高效使用 rAF 需要仔细规划,尤其是在处理多个动画时。
在本文中,我们将探讨如何通过集中动画管理、引入 FPS 控制以及保持浏览器主线程响应来优化 requestAnimationFrame。
了解 FPS 及其重要性
在讨论动画性能时,每秒帧数 (FPS) 至关重要。大多数屏幕以 60 FPS 刷新,这意味着 requestAnimationFrame 每秒被调用 60 次。为了保持流畅的动画,浏览器必须在每帧约 16.67 毫秒内完成其工作。
如果在单个帧中运行太多任务,浏览器可能会错过其目标帧时间,从而导致卡顿或丢帧。降低某些动画的 FPS 有助于减少主线程的负载,从而在性能和流畅度之间取得平衡。
具有 FPS 控制功能的集中式动画管理器可实现更好的性能
为了更有效地管理动画,我们可以通过共享循环集中处理动画,而不是在代码中分散多个 requestAnimationFrame 调用。集中式方法可最大程度地减少冗余调用,并更轻松地添加 FPS 控制。
下面的AnimationManager类允许我们在控制目标FPS的同时注册和取消注册动画任务。默认情况下,我们的目标是 60 FPS,但这可以根据性能需求进行调整。
class AnimationManager { private tasks: Set<framerequestcallback> = new Set(); private fps: number = 60; // Target FPS private lastFrameTime: number = performance.now(); private animationId: number | null = null; // Store the animation frame ID private run = (currentTime: number) => { const deltaTime = currentTime - this.lastFrameTime; // Ensure the tasks only run if enough time has passed to meet the target FPS if (deltaTime > 1000 / this.fps) { this.tasks.forEach((task) => task(currentTime)); this.lastFrameTime = currentTime; } this.animationId = requestAnimationFrame(this.run); }; public registerTask(task: FrameRequestCallback) { this.tasks.add(task); if (this.tasks.size === 1) { this.animationId = requestAnimationFrame(this.run); // Start the loop if this is the first task } } public unregisterTask(task: FrameRequestCallback) { this.tasks.delete(task); if (this.tasks.size === 0 && this.animationId !== null) { cancelAnimationFrame(this.animationId); // Stop the loop if no tasks remain this.animationId = null; // Reset the ID } } } export const animationManager = new AnimationManager(); </framerequestcallback>
在此设置中,我们计算帧之间的 deltaTime,以确定基于目标 FPS 是否已经过去了足够的时间进行下一次更新。这使我们能够限制更新频率,以确保浏览器的主线程不会过载。
实际示例:为具有不同属性的多个元素设置动画
让我们创建一个示例,其中我们为三个盒子设置动画,每个盒子都有不同的动画:一个缩放,另一个改变颜色,第三个旋转。
这是 HTML:
<div id="animate-box-1" class="animated-box"></div> <div id="animate-box-2" class="animated-box"></div> <div id="animate-box-3" class="animated-box"></div>
这是 CSS:
.animated-box { width: 100px; height: 100px; background-color: #3498db; transition: transform 0.1s ease; }
现在,我们将添加 JavaScript 来为每个具有不同属性的框设置动画。一个会缩放,另一个会改变颜色,第三个会旋转。
第 1 步:添加线性插值 (lerp)
线性插值 (lerp) 是动画中常用的技术,用于在两个值之间平滑过渡。它有助于创建渐进且平滑的进程,使其成为随时间推移缩放、移动或更改属性的理想选择。该函数采用三个参数:起始值、结束值和标准化时间 (t),该时间确定过渡的距离。
function lerp(start: number, end: number, t: number): number { return start + (end - start) * t; }
第 2 步:缩放动画
我们首先创建一个函数来为第一个框的缩放设置动画:
function animateScale( scaleBox: HTMLDivElement, startScale: number, endScale: number, speed: number ) { let scaleT = 0; function scale() { scaleT += speed; if (scaleT > 1) scaleT = 1; const currentScale = lerp(startScale, endScale, scaleT); scaleBox.style.transform = `scale(${currentScale})`; if (scaleT === 1) { animationManager.unregisterTask(scale); } } animationManager.registerTask(scale); }
第 3 步:彩色动画
接下来,我们为第二个框的颜色变化设置动画:
function animateColor( colorBox: HTMLDivElement, startColor: number, endColor: number, speed: number ) { let colorT = 0; function color() { colorT += speed; if (colorT > 1) colorT = 1; const currentColor = Math.floor(lerp(startColor, endColor, colorT)); colorBox.style.backgroundColor = `rgb(${currentColor}, 100, 100)`; if (colorT === 1) { animationManager.unregisterTask(color); } } animationManager.registerTask(color); }
第 4 步:旋转动画
最后,我们创建旋转第三个框的函数:
function animateRotation( rotateBox: HTMLDivElement, startRotation: number, endRotation: number, speed: number ) { let rotationT = 0; function rotate() { rotationT += speed; // Increment progress if (rotationT > 1) rotationT = 1; const currentRotation = lerp(startRotation, endRotation, rotationT); rotateBox.style.transform = `rotate(${currentRotation}deg)`; // Unregister task once the animation completes if (rotationT === 1) { animationManager.unregisterTask(rotate); } } animationManager.registerTask(rotate); }
第 5 步:开始动画
最后,我们可以启动所有三个盒子的动画:
// Selecting the elements const scaleBox = document.querySelector("#animate-box-1") as HTMLDivElement; const colorBox = document.querySelector("#animate-box-2") as HTMLDivElement; const rotateBox = document.querySelector("#animate-box-3") as HTMLDivElement; // Starting the animations animateScale(scaleBox, 1, 1.5, 0.02); // Scaling animation animateColor(colorBox, 0, 255, 0.01); // Color change animation animateRotation(rotateBox, 360, 1, 0.005); // Rotation animation
主线程注意事项
使用 requestAnimationFrame 时,必须记住动画在浏览器的主线程上运行。主线程超载过多的任务可能会导致浏览器错过动画帧,从而导致卡顿。这就是为什么使用集中式动画管理器和 FPS 控制等工具优化动画可以帮助保持流畅度,即使有多个动画也是如此。
结论
在 JavaScript 中有效管理动画需要的不仅仅是使用 requestAnimationFrame。通过集中动画并控制 FPS,您可以确保动画更流畅、性能更高,同时保持主线程响应能力。在此示例中,我们展示了如何使用单个 AnimationManager 处理多个动画,演示如何优化性能和可用性。虽然为了简单起见,我们专注于保持一致的 FPS,但这种方法可以扩展到处理各种动画的不同 FPS 值,尽管这超出了本文的范围。
Github 存储库: https://github.com/JBassx/rAF-optimization
StackBlitz: https://stackblitz.com/~/github.com/JBassx/rAF-optimization
领英: https://www.linkedin.com/in/josephciullo/
以上是增强您的 Web 动画:像专业人士一样优化 requestAnimationFrame的详细内容。更多信息请关注PHP中文网其他相关文章!

Python和JavaScript的主要区别在于类型系统和应用场景。1.Python使用动态类型,适合科学计算和数据分析。2.JavaScript采用弱类型,广泛用于前端和全栈开发。两者在异步编程和性能优化上各有优势,选择时应根据项目需求决定。

选择Python还是JavaScript取决于项目类型:1)数据科学和自动化任务选择Python;2)前端和全栈开发选择JavaScript。Python因其在数据处理和自动化方面的强大库而备受青睐,而JavaScript则因其在网页交互和全栈开发中的优势而不可或缺。

Python和JavaScript各有优势,选择取决于项目需求和个人偏好。1.Python易学,语法简洁,适用于数据科学和后端开发,但执行速度较慢。2.JavaScript在前端开发中无处不在,异步编程能力强,Node.js使其适用于全栈开发,但语法可能复杂且易出错。

javascriptisnotbuiltoncorc; saninterpretedlanguagethatrunsonenginesoftenwritteninc.1)javascriptwasdesignedAsalightweight,解释edganguageforwebbrowsers.2)Enginesevolvedfromsimpleterterterpretpreterterterpretertestojitcompilerers,典型地提示。

JavaScript可用于前端和后端开发。前端通过DOM操作增强用户体验,后端通过Node.js处理服务器任务。1.前端示例:改变网页文本内容。2.后端示例:创建Node.js服务器。

选择Python还是JavaScript应基于职业发展、学习曲线和生态系统:1)职业发展:Python适合数据科学和后端开发,JavaScript适合前端和全栈开发。2)学习曲线:Python语法简洁,适合初学者;JavaScript语法灵活。3)生态系统:Python有丰富的科学计算库,JavaScript有强大的前端框架。

JavaScript框架的强大之处在于简化开发、提升用户体验和应用性能。选择框架时应考虑:1.项目规模和复杂度,2.团队经验,3.生态系统和社区支持。

引言我知道你可能会觉得奇怪,JavaScript、C 和浏览器之间到底有什么关系?它们之间看似毫无关联,但实际上,它们在现代网络开发中扮演着非常重要的角色。今天我们就来深入探讨一下这三者之间的紧密联系。通过这篇文章,你将了解到JavaScript如何在浏览器中运行,C 在浏览器引擎中的作用,以及它们如何共同推动网页的渲染和交互。JavaScript与浏览器的关系我们都知道,JavaScript是前端开发的核心语言,它直接在浏览器中运行,让网页变得生动有趣。你是否曾经想过,为什么JavaScr


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。

WebStorm Mac版
好用的JavaScript开发工具

mPDF
mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

Dreamweaver CS6
视觉化网页开发工具