写window.requestAnimationFrame(回调函数)
时,浏览器会在下次重绘前执行回调函数。
我们可以用它来做连贯的逐帧动画,在没有requestAnimationFrame
方法之前,我们只能用setTimeout
或setInterval
来实现类似的效果,这样写的存在的问题是:如果浏览器不是每秒60帧,会造成掉帧。
window.requestAnimFrame= (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
window.cancelRequestAnimFrame = window.cancelRequestAnimationFrame
|| window.webkitCancelAnimationFrame
|| window.webkitCancelRequestAnimationFrame
|| window.mozCancelRequestAnimationFrame
|| window.oCancelRequestAnimationFrame
|| window.msCancelRequestAnimationFrame
|| clearTimeout;
react项目中有字体广播滚动消息循环:
部分代码分享
animation(){
this.timer=window.requestAnimFrame(function(){
++this.dis;
this.refs.adNotice.style.transform ="translateX(-" + this.dis + 'px)';
if(this.dis<this.a){
this.animation();
}else{
this.dis=0;
cancelRequestAnimFrame(this.timer);
this.refs.adNotice.style.transform ="translateX(0px)";
this.animation();
}
}.bind(this))
}