2019-12-03
描述
在每一帧动画前调用提供的回调函数。
提示
- 需使用递归
- 变量
running
为true
时,将持续调用已提供回调函数的window.requestAnimationFrame()
- 对象中应包含
start
和stop
两个方法,以便手工对记录状态进行控制 - 第二个参数
autoStart
默认值为true
。当运行该函数时,默认调用start
方法
代码
const recordAnimationFrames = (callback, autoStart = true) => { let running = true, raf; const stop = () => { running = false; cancelAnimationFrame(raf); }; const start = () => { running = true; run(); }; const run = () => { raf = requestAnimationFrame(() => { callback(); if (running) run(); }); }; if (autoStart) start(); return { start, stop }; };
示例
在每一帧动画前打印日志:
const cb = () => console.log('Animation frame fired'); const recorder = recordAnimationFrames(cb); // 在每一帧之前打印 'Animation frame fired' recorder.stop(); // 停止执行回调函数 recorder.start(); // 再次开启 const recorder2 = recordAnimationFrames(cb, false); // 在每一帧记录前需要明确的执行 `start`