From 6ebddae4355f4ca6475bf0fe5933c6418124a82b Mon Sep 17 00:00:00 2001 From: Luca Conte Date: Thu, 6 Mar 2025 15:59:26 +0100 Subject: [PATCH] add stats display --- src/index.html | 20 +++++++++++++++++++- src/script.js | 32 +++++++++++++++++++++++++++++++- 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/src/index.html b/src/index.html index 441e5a3..465697f 100644 --- a/src/index.html +++ b/src/index.html @@ -9,19 +9,37 @@ +
+
FPS:
+
Frame time:
+
\ No newline at end of file diff --git a/src/script.js b/src/script.js index ba81828..3ec882c 100644 --- a/src/script.js +++ b/src/script.js @@ -6,6 +6,8 @@ let program; let vertexBuffer; +let lastFrame = Date.now(); + async function init() { cv = document.getElementById("cv"); gl = cv.getContext("webgl"); @@ -50,7 +52,7 @@ async function init() { 5 * Float32Array.BYTES_PER_ELEMENT, // size of individual vertex / distance between values to read 0 // offset where to start reading ); - + // enable attribute gl.enableVertexAttribArray(positionAttribLocation); @@ -75,7 +77,34 @@ async function init() { requestAnimationFrame(draw); } +let frameCount = 0; +let lastStatUpdate = Date.now(); + +function updateStats(deltaTime) { + frameCount++; + + let now = Date.now(); + let timeSinceLastUpdate = (now - lastStatUpdate) / 1000; + + if (timeSinceLastUpdate < 0.5) return; + + lastStatUpdate = now; + + let fpsDisplay = document.getElementById("fps"); + fpsDisplay.innerText = Math.round(frameCount / timeSinceLastUpdate) + + let msDisplay = document.getElementById("ms"); + msDisplay.innerText = deltaTime * 1000 + "ms"; + + frameCount = 0; +} + async function draw() { + let now = Date.now(); + let deltaTime = (now - lastFrame) / 1000; + + updateStats(deltaTime); + gl.clear(gl.COLOR_BUFFER_BIT); gl.useProgram(program); @@ -84,6 +113,7 @@ async function draw() { gl.drawArrays(gl.TRIANGLES, 0, 3); + lastFrame = now; requestAnimationFrame(draw); }