Skip to content

Commit 887e063

Browse files
authored
Add FPS counter overlay to WASM demo (#22)
1 parent 2ef071b commit 887e063

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

wasm/game.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,10 @@
11
const canvas = document.getElementById('game-canvas');
22
const context = canvas.getContext('2d');
3+
const fpsDisplay = document.getElementById('fps-counter');
34
let wasmExports = null;
45
let lastTime = null;
6+
let fpsFrameCount = 0;
7+
let fpsLastTimestamp = 0;
58

69
function resizeCanvas() {
710
canvas.width = window.innerWidth;
@@ -34,6 +37,7 @@ function drawFrame() {
3437
function updateAndRender(timestamp) {
3538
if (!lastTime) {
3639
lastTime = timestamp;
40+
fpsLastTimestamp = timestamp;
3741
}
3842

3943
const deltaSeconds = (timestamp - lastTime) / 1000;
@@ -42,6 +46,17 @@ function updateAndRender(timestamp) {
4246
wasmExports.update(deltaSeconds);
4347
drawFrame();
4448

49+
fpsFrameCount += 1;
50+
const fpsElapsed = timestamp - fpsLastTimestamp;
51+
if (fpsElapsed >= 250) {
52+
const fps = Math.round((fpsFrameCount * 1000) / fpsElapsed);
53+
if (fpsDisplay) {
54+
fpsDisplay.textContent = `${fps} FPS`;
55+
}
56+
fpsFrameCount = 0;
57+
fpsLastTimestamp = timestamp;
58+
}
59+
4560
requestAnimationFrame(updateAndRender);
4661
}
4762

wasm/index.html

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,29 @@
3737
height: 100%;
3838
display: block;
3939
}
40+
41+
#fps-counter {
42+
position: fixed;
43+
top: 1rem;
44+
left: 1rem;
45+
padding: 0.25rem 0.75rem;
46+
border-radius: 9999px;
47+
background: rgba(15, 23, 42, 0.75);
48+
color: #facc15;
49+
font-weight: 600;
50+
font-size: 0.875rem;
51+
letter-spacing: 0.02em;
52+
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
53+
backdrop-filter: blur(6px);
54+
pointer-events: none;
55+
}
4056
</style>
4157
</head>
4258
<body>
4359
<h1>WebAssembly Bouncing Ball Demo</h1>
4460
<p>The ball is simulated inside WebAssembly and rendered on an HTML canvas.</p>
4561
<canvas id="game-canvas"></canvas>
62+
<div id="fps-counter" role="status" aria-live="polite">-- FPS</div>
4663
<script type="module" src="game.js"></script>
4764
</body>
4865
</html>

0 commit comments

Comments
 (0)