gpt4 book ai didi

javascript - 使用 requestAnimationFrame 在 Canvas 中计算 FPS

转载 作者:IT王子 更新时间:2023-10-29 03:17:57 31 4
gpt4 key购买 nike

如何计算 Canvas 游戏应用程序的 FPS?我看过一些例子,但没有一个使用 requestAnimationFrame,我不确定如何在那里应用他们的解决方案。这是我的代码:

(function(window, document, undefined){

var canvas = document.getElementById("mycanvas"),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height,
fps = 0,
game_running = true,
show_fps = true;

function showFPS(){
context.fillStyle = "Black";
context.font = "normal 16pt Arial";

context.fillText(fps + " fps", 10, 26);
}
function gameLoop(){

//Clear screen
context.clearRect(0, 0, width, height);

if (show_fps) showFPS();

if (game_running) requestAnimationFrame(gameLoop);

}

gameLoop();

}(this, this.document))
canvas{
border: 3px solid #fd3300;
}
<canvas id="mycanvas" width="300" height="150"></canvas>

顺便问一下,我可以添加任何库来监督性能吗?

最佳答案

不要使用new Date()

此 API 有几个缺陷,仅对获取当前日期和时间有用。不适用于测量时间跨度。

Date-API 使用操作系统的内部时钟,该时钟不断更新并与 NTP 时间服务器同步。这意味着,这个时钟的速度/频率有时比实际时间快,有时慢 - 因此不能用于测量持续时间和帧率。

如果有人更改系统时间(手动或由于 DST),如果单个帧突然需要一个小时,您至少可以看到问题。或者消极的时间。但如果系统时钟快 20% 以与世界时间同步,则几乎不可能检测到。

此外,Date-API 非常不精确 - 通常远小于 1 毫秒。这使得它对于帧速率测量尤其无用,其中一个 60Hz 帧需要约 17 毫秒。

改为使用 performance.now()

Performance API 专为此类用例而设计,可等效于 new Date() 使用。只需选择其他答案之一并将 new Date() 替换为 performance.now(),您就可以开始了。

来源:

Also unlike Date.now(), the values returned by Performance.now() always increase at a constant rate, independent of the system clock (which might be adjusted manually or skewed by software like NTP). Otherwise, performance.timing.navigationStart + performance.now() will be approximately equal to Date.now().

https://developer.mozilla.org/en-US/docs/Web/API/Performance/now

对于 Windows:

[The time service] adjusts the local clock rate to allow it to converge toward the correct time. If the time difference between the local clock and the [accurate time sample] is too large to correct by adjusting the local clock rate, the time service sets the local clock to the correct time.

https://technet.microsoft.com/en-us/library/cc773013(v=ws.10).aspx

关于javascript - 使用 requestAnimationFrame 在 Canvas 中计算 FPS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8279729/

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