gpt4 book ai didi

javascript - 这个 requestAnimationFrame polyfill 也会产生时间戳吗?

转载 作者:行者123 更新时间:2023-12-03 08:00:20 24 4
gpt4 key购买 nike

(function() {
var lastTime = 0;
var vendors = ['webkit', 'moz'];
for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x]+'RequestAnimationFrame'];
window.cancelAnimationFrame =
window[vendors[x]+'CancelAnimationFrame'] || window[vendors[x]+'CancelRequestAnimationFrame'];
}

if (!window.requestAnimationFrame)
window.requestAnimationFrame = function(callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);
lastTime = currTime + timeToCall;
return id;
};

if (!window.cancelAnimationFrame)
window.cancelAnimationFrame = function(id) {
clearTimeout(id);
};
}());

取自https://gist.github.com/paulirish/1579671 。在第一个 if 语句中,它测试 requestAnimationFrame 是否作为窗口属性存在。在此 if 语句中,它创建了补偿所需的超时,但它是否也创建了要传递到调用的函数中的时间戳? element 参数有什么作用?我想我需要有人帮助我理解这里发生的事情。

这是一个用例来显示我所指的时间戳:

var id = null,
start_time = null,
time_passed = null;

function loop( timestamp ){

if( !start_time ) start_time = timestamp;

time_passed = timestamp - start_time;

if( time_passed < 1000 ){
id = requestAnimationFrame( loop );
}

}

id = requestAnimationFrame( loop );

最佳答案

第一个循环只是通过检查 window-object 中是否存在 vendor 前缀变体来测试 window.requestAnimationFramewindow.cancelAnimationFrame 是否存在>.

element 参数已被弃用,如 http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/ 中所示。

You’ll also notice the second parameter to requestAnimFrame: the element that visually bounds the entire animation. For canvas and WebGL, this will be the actual element. For DOM stuff, you can leave it off or define it for a slightly more optimized experience. It’s since been removed from the spec (and WebKit’s implementation)

它将当前时间戳传递给回调函数:

var id = window.setTimeout(function() { callback(currTime + timeToCall); },
timeToCall);

其中 currTime + timeToCall 是调用函数的时刻。然后,您可以像在示例中一样,在动画函数中将其用作第一个参数:

function loop(time){
//time === current time
}

关于javascript - 这个 requestAnimationFrame polyfill 也会产生时间戳吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34607703/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com