requestAnimationFrame是一个新的浏览器特性,其优势在于允许浏览器主动控制并优化动画的绘制,通过这个API可以实现更可靠的定时器。
假设我们想每秒钟让一张图片出现在画布的随机位置上,传统的写法是这样的
1 2 3 4 5 6 7 8 9 10 11
| setInterval(() => { let image = document.getElementById('image'); document .getElementById('myCanvas') .getContext('2d') .drawImage( image, Math.floor(Math.random()*100), Math.floor(Math.random()*100) ) }, 1000);
|
使用requestAnimationFrame的写法如下所示
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| let lastRefresh = 0; let randomImage = (time) => { if(time - lastRefresh > 1000) { lastRefresh = time; let image = document.getElementById('image'); document .getElementById('myCanvas') .getContext('2d') .drawImage( image, Math.floor(Math.random()*100), Math.floor(Math.random()*100) ) } requestAnimationFrame(randomImage); }
requestAnimationFrame(randomImage);
|
然而不同的浏览器对这个API的实现有一些差异。有大佬写了一段多浏览器兼容代码,直接复制粘贴,在调用requestAnimationFrame之前执行即可
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
if (!window.requestAnimationFrame) { window.requestAnimationFrame = (function () { return ( window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || function (callback) { window.setTimeout(callback, 1000 / 60); } ); })(); }
|