requestAnimationFrame

是什么

是 window 对象的 API,可以通过调用 window.requestAnimationFrame( callback ) 来配置下次浏览器重绘前需要执行的功能(即传入的 callback 参数)。

解决什么问题

通过 window.requestAnimationFrame 来更新动画,可以有效提升页面的帧率,使得动画更流畅。

用法

1
window.requestAnimationFrame( callback );
  • callback

    callback 参数是下次重回前需要调用的函数,该回调函数会被传入 requestAnimationFrame() 开始去执行回调函数的时刻。

  • 返回值

    一个 long 整数的请求 ID(非零) ,是回调列表中唯一的标识。可以传这个值给 window.cancelAnimationFrame() 来取消回调函数

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var start = null;
var element = document.getElementById('SomeElementYouWantToAnimate');
element.style.position = 'absolute';

function step(timestamp) {
if (!start) start = timestamp;
var progress = timestamp - start;
element.style.left = Math.min(progress / 10, 200) + 'px';
if (progress < 2000) {
window.requestAnimationFrame(step);
}
}

window.requestAnimationFrame(step);

注意

  • 在同一个帧中的多个回调函数,会接受到相同的时间戳,该时间戳是一个十进制数,单位毫秒,最小精度为1ms(1000μs)
  • 在大多数浏览器里,当 requestAnimationFrame() 运行在后台标签页或者隐藏的 iframe 里时,requestAnimationFrame() 会被暂停调用以提升性能。