gpt4 book ai didi

javascript - 如何将动画帧精确锁定为 1 秒?

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

如果我尝试多次运行 JSfiddle 中发布的代码,我会得到不同数量的 div(我假设animeframe 并未在 1 秒内完全完成)

http://jsfiddle.net/ghjKC/133/

    // shim layer with setTimeout fallback
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element){
return window.setTimeout(callback, 1000 / 60);
};
})();
window.cancelRequestAnimFrame = ( function() {
return window.cancelAnimationFrame ||
window.webkitCancelRequestAnimationFrame ||
window.mozCancelRequestAnimationFrame ||
window.oCancelRequestAnimationFrame ||
window.msCancelRequestAnimationFrame ||
clearTimeout
} )();

var request;

(function animloop(){
console.log("render() should be done here and now");
request = requestAnimFrame(animloop, $("#time").append("<div></div>"));
})();

// cancelRequestAnimFrame to stop the loop in 1sec
console.log("will do cancelRequestAnimFrame in 1sec...")
setTimeout(function(){
console.log("1sec expired doing cancelRequestAnimFrame() now")
cancelRequestAnimFrame(request);
}, 1*1000)

我的问题是如何确保我获得相同数量的 div?

最佳答案

无法保证 setTimeout 的精度和requestAnimationFrame回调。

setTimeout相当不精确。

requestAnimationFrame取决于您的系统渲染页面的速度。如果页面非常复杂,帧率下降,回调的调用次数将远低于每秒60次。

现在,如果您解释一下您的实际问题是什么,我们就可以尝试找到一个好的解决方案。

你说你想要一个常数 <div> ,这意味着执行次数恒定。这是时间无法控制的。根据您的用例,您可以直接控制执行次数。例如。运行回调 60 次(理想情况下, requestAnimationFrame 接近 1 秒)。

编辑根据您的评论:如果您想做一个在 1 秒内平滑填充的进度条。最好的方法是:使用 requestAnimationFrame ,传递给回调的第一个参数是高精度时间。由此计算您应该填充进度条多少。如果时间> 1秒,则不再请求另一帧。

主要思想:

var startTime;

function startProgress() {
startTime = null;
requestAnimationFrame(progress);
}

function progress(time) {
if (startTime === null) startTime = time;
// Compute progress since last frame
var ratio = (time - startTime) / 1000; // time is in [ms]
// Here you should update your progress, maybe this:
// Note I've used Math.min because we might go over 100% due to callback time.
$(".progressDiv").width(Math.min(ratio, 1) * 300);
// If we're not done yet, request a new animation frame
if (ratio < 1) requestAnimationFrame(progress);
}

关于javascript - 如何将动画帧精确锁定为 1 秒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25240067/

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