Optimizing Konva Performance with rAF
Introduction
requestAnimationFrame (rAF) is a powerful browser API that helps achieve smoother interface changes by synchronizing rendering with the screen's refresh rate. Using rAF helps optimize performance, minimize lag (jank), and save energy by pausing calculations when the browser tab is inactive.
Prerequisites
In this article, I will continue to use the example from the previous article to optimize, so I will not provide the complete code but only the updated part; please refer to the previous article for the full content.
Detail
Update the OptimizedCanvas.tsx file as follows:
- The above code implements a Throttling mechanism via requestAnimationFrame to optimize updating the viewRect state when the user performs drag or zoom operations. By using requestRef to manage and cancel pending frames, the application ensures coordinate calculation occurs only once per screen refresh, combined with the Culling mechanism (rendering only visible elements) to significantly reduce CPU/GPU load when processing large numbers of objects.
- Using requestAnimationFrame with a function passed inside means requesting that this function be executed before the next frame is drawn.
- Note that cancelAnimationFrame only cancels the previously scheduled function execution, not the frame drawing itself.
- Using requestAnimationFrame (rAF) to wrap the setViewRect command is a Debouncing/Throttling technique based on the screen's refresh rate. When you scroll or drag extremely fast, the onWheel and onDragMove events can fire hundreds of times per second, exceeding the smooth processing capability of React State and the screen's refresh rate.
- Most screens today have a frequency of 60Hz (16.7ms/frame). If you scroll extremely fast, the browser may send 100 wheel events/second.
- Without rAF: React attempts to re-render 100 times. This causes CPU churning, lag, and dropped frames.
- With rAF: React updates at most 60 times/second, perfectly aligned with when the browser prepares to draw on the screen.
You can enable the Frame Rendering Stats function to see that the FPS level and GPU consumption have been optimized stably.
Happy coding!
Comments
Post a Comment