我是动画新手,但我最近使用setTimeout
创建了一个动画。FPS太低了,所以我找到了使用requestAnimationFrame
的解决方案,在这篇link中描述了这一点。
到目前为止,我的代码是:
//shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback){
window.setTimeout(callback, 1000 / 60);
};
})();
(function animloop(){
//Get metrics
var leftCurveEndX = finalLeft - initialLeft;
var leftCurveEndY = finalTop + finalHeight - initialTop;
var rightCurveEndX = finalLeft + finalWidth - initialLeft - initialWidth;
var rightCurveEndY = leftCurveEndY;
chopElement(0, 0, 0, 0, leftCurveEndX, leftCurveEndY, rightCurveEndX, rightCurveEndY);//Creates a new frame
requestAnimFrame(animloop);
})();
这会在第一帧停止。我在chopElement
函数中有一个回调函数requestAnimFrame(animloop);
。
另外,有没有更全面的API使用指南?
发布于 2013-08-06 09:39:15
/*
Provides requestAnimationFrame in a cross browser way.
http://paulirish.com/2011/requestanimationframe-for-smart-animating/
*/
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = (function() {
return window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame || // comment out if FF4 is slow (it caps framerate at ~30fps: https://bugzilla.mozilla.org/show_bug.cgi?id=630127)
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function( /* function FrameRequestCallback */ callback, /* DOMElement Element */ element) {
window.setTimeout(callback, 1000 / 60);
};
})();
}
animate();
function animate() {
requestAnimationFrame(animate);
draw();
}
function draw() {
// Put your code here
}
看看下面的jsfiddle示例;它清楚地说明了我的意思;
http://jsfiddle.net/XQpzU/4358/light/
希望这能有所帮助!
发布于 2014-03-18 04:49:40
“智能节流,这样事件就不会被触发的次数超过屏幕重绘更改的次数:
var requestFrame = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
// polyfill - throttle fall-back for unsupported browsers
(function() {
var throttle = false,
FPS = 1000 / 60; // 60fps (in ms)
return function(CB) {
if( throttle ) return;
throttle = true;
setTimeout(function(){ throttle = false }, FPS);
CB(); // do your thing
}
})();
/////////////////////////////
// use case:
function doSomething() {
console.log('fired');
}
window.onscroll = function() {
requestFrame(doSomething);
};
html, body{ height:300%; }
body::before{ content:'scroll here'; position:fixed; font:2em Arial; }
https://stackoverflow.com/questions/5605588
复制相似问题