理解请求动画框架

Understanding requestanimationframe

我正在努力理解 requestanimationframe

requestanimationframe 是一个浏览器 API 使影响绘制的用户界面的逻辑在 运行 之前尽最大努力完成的浏览器是否正确图形子系统接口的下一个 blitting,以避免由于物理屏幕刷新周期和应用程序渲染循环之间的相位差而浪费精力绘制永远不会出现在屏幕上的帧?

requestAnimationFrame 只是一个 method 其中:

The requestAnimationFrame method is used to signal to the user agent that a script-based animation needs to be resampled.

调用方法时:

When requestAnimationFrame(callback) is called, the user agent MUST schedule a script-based animation resampling by appending to the end of the animation frame request callback list an entry whose handle is a user-agent-defined integer greater than zero that uniquely identifies the entry in the list and whose callback is callback.

下一步是遍历回调列表(除非已为仍在列表中的一个或多个 ID 调用了 cancelAnimationFrame) browser issues a repaint.

The Window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint.

rAF 将同步每个回调,以便每个重绘适合显示器(或显示卡)的更新速率 (VBLANK)。这基本上意味着在 VBLANK 发生后立即发出新的回调,以便脚本在下一个 VBLANK 触发之前有大约 16.7 毫秒的时间完成渲染。

A setTimeout/setInterval 无法与监视器更新同步,因为它们只能采用整数值。通常的更新率需要每帧 16.67 毫秒 @ 60 赫兹,因此您会不时使用其中一种方法获得 "jerks",因为您需要使用 16 或 17 毫秒的更新率。

rAF 不受此限制。由于 rAF 正在处理帧更新列表而不是公共事件列表,浏览器可以更有效地清除队列。浏览器还可以将速率降低到 f.ex。如果浏览器选项卡不可见,则减半将回调减半,从而减少负载。

没有要求使用图形子系统来 "blit"/重绘,但通常是这样。