增強您的 Web 動畫:像專業人士一樣最佳化 requestAnimationFrame
Smooth and performant animations are essential in modern web applications. However, managing them improperly can overload the browser’s main thread, causing poor performance and janky animations. requestAnimationFrame (rAF) is a browser API designed to sync animations with the display's refresh rate, ensuring smoother motion compared to alternatives like setTimeout. But using rAF efficiently requires careful planning, especially when handling multiple animations.
In this article, we will explore how to optimize requestAnimationFrame by centralizing animation management, introducing FPS control, and keeping the browser’s main thread responsive.
Understanding FPS and Why It Matters
Frames per second (FPS) is crucial when discussing animation performance. Most screens refresh at 60 FPS, meaning that requestAnimationFrame is called 60 times per second. To maintain smooth animations, the browser must complete its work within about 16.67 milliseconds per frame.
If too many tasks run during a single frame, the browser might miss its target frame time, causing stuttering or dropped frames. Lowering the FPS for certain animations can help reduce the load on the main thread, providing a balance between performance and smoothness.
Centralized Animation Manager with FPS Control for Better Performance
To manage animations more efficiently, we can centralize their handling with a shared loop rather than having multiple requestAnimationFrame calls scattered throughout the code. A centralized approach minimizes redundant calls and makes it easier to add FPS control.
The following AnimationManager class allows us to register and unregister animation tasks while controlling the target FPS. By default, we aim for 60 FPS, but this can be adjusted for performance needs.
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();
In this setup, we calculate the deltaTime between frames to determine if enough time has passed for the next update based on the target FPS. This allows us to throttle the frequency of updates to ensure the browser’s main thread isn’t overloaded.
Practical Example: Animating Multiple Elements with Different Properties
Let’s create an example where we animate three boxes, each with a different animation: one scales, another changes color, and the third rotates.
Here’s the 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>
Here’s the CSS:
.animated-box { width: 100px; height: 100px; background-color: #3498db; transition: transform 0.1s ease; }
Now, we’ll add JavaScript to animate each box with a different property. One will scale, another will change its color, and the third will rotate.
Step 1: Adding Linear Interpolation (lerp)
Linear interpolation (lerp) is a common technique used in animations to smoothly transition between two values. It helps create a gradual and smooth progression, making it ideal for scaling, moving, or changing properties over time. The function takes three parameters: a starting value, an ending value, and a normalized time (t), which determines how far along the transition is.
function lerp(start: number, end: number, t: number): number { return start + (end - start) * t; }
Step 2: Scaling Animation
We start by creating a function to animate the scaling of the first box:
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); }
Step 3: Color Animation
Next, we animate the color change of the second box:
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); }
Step 4: Rotation Animation
Finally, we create the function to rotate the third box:
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); }
Step 5: Starting the Animations
Finally, we can start the animations for all three boxes:
// 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
Note on the Main Thread
When using requestAnimationFrame, it’s essential to keep in mind that animations run on the browser’s main thread. Overloading the main thread with too many tasks can cause the browser to miss animation frames, resulting in stuttering. This is why optimizing your animations with tools like a centralized animation manager and FPS control can help maintain smoothness, even with multiple animations.
Conclusion
Managing animations efficiently in JavaScript requires more than just using requestAnimationFrame. By centralizing animations and controlling the FPS, you can ensure smoother, more performant animations while keeping the main thread responsive. In this example, we showed how to handle multiple animations with a single AnimationManager, demonstrating how to optimize for both performance and usability. While we focused on maintaining a consistent FPS for simplicity, this approach can be expanded to handle different FPS values for various animations, though that was beyond the scope of this article.
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中文網其他相關文章!

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

Python更適合初學者,學習曲線平緩,語法簡潔;JavaScript適合前端開發,學習曲線較陡,語法靈活。 1.Python語法直觀,適用於數據科學和後端開發。 2.JavaScript靈活,廣泛用於前端和服務器端編程。

從C/C 轉向JavaScript需要適應動態類型、垃圾回收和異步編程等特點。 1)C/C 是靜態類型語言,需手動管理內存,而JavaScript是動態類型,垃圾回收自動處理。 2)C/C 需編譯成機器碼,JavaScript則為解釋型語言。 3)JavaScript引入閉包、原型鍊和Promise等概念,增強了靈活性和異步編程能力。

JavaScript在Web開發中的主要用途包括客戶端交互、表單驗證和異步通信。 1)通過DOM操作實現動態內容更新和用戶交互;2)在用戶提交數據前進行客戶端驗證,提高用戶體驗;3)通過AJAX技術實現與服務器的無刷新通信。

JavaScript在現實世界中的應用包括前端和後端開發。 1)通過構建TODO列表應用展示前端應用,涉及DOM操作和事件處理。 2)通過Node.js和Express構建RESTfulAPI展示後端應用。

理解JavaScript引擎內部工作原理對開發者重要,因為它能幫助編寫更高效的代碼並理解性能瓶頸和優化策略。 1)引擎的工作流程包括解析、編譯和執行三個階段;2)執行過程中,引擎會進行動態優化,如內聯緩存和隱藏類;3)最佳實踐包括避免全局變量、優化循環、使用const和let,以及避免過度使用閉包。

Python和JavaScript在社區、庫和資源方面的對比各有優劣。 1)Python社區友好,適合初學者,但前端開發資源不如JavaScript豐富。 2)Python在數據科學和機器學習庫方面強大,JavaScript則在前端開發庫和框架上更勝一籌。 3)兩者的學習資源都豐富,但Python適合從官方文檔開始,JavaScript則以MDNWebDocs為佳。選擇應基於項目需求和個人興趣。

Python和JavaScript在開發環境上的選擇都很重要。 1)Python的開發環境包括PyCharm、JupyterNotebook和Anaconda,適合數據科學和快速原型開發。 2)JavaScript的開發環境包括Node.js、VSCode和Webpack,適用於前端和後端開發。根據項目需求選擇合適的工具可以提高開發效率和項目成功率。

C和C 在JavaScript引擎中扮演了至关重要的角色,主要用于实现解释器和JIT编译器。1)C 用于解析JavaScript源码并生成抽象语法树。2)C 负责生成和执行字节码。3)C 实现JIT编译器,在运行时优化和编译热点代码,显著提高JavaScript的执行效率。
