Make FPS display look better

This commit is contained in:
Bill Rossi 2025-06-07 11:17:57 -04:00
parent 499814553f
commit 9ea7564ac8
2 changed files with 21 additions and 4 deletions

View File

@ -3,6 +3,8 @@ import Input from "./input.js"
import Event from "./event.js" import Event from "./event.js"
import Message from "./message.js" import Message from "./message.js"
import { average } from "./util.js"
export default class Game { export default class Game {
constructor(canvas) { constructor(canvas) {
this.canvas = canvas this.canvas = canvas
@ -21,6 +23,8 @@ export default class Game {
} }
this.message = null this.message = null
this.fpsBuffer = [60, 60, 60, 60, 60, 60, 60, 60, 60, 60]
} }
triggerEvent(eventName, object) { triggerEvent(eventName, object) {
@ -45,6 +49,9 @@ export default class Game {
loop(timestamp) { loop(timestamp) {
this.dt = timestamp - this.timestamp this.dt = timestamp - this.timestamp
const fps = 1000 / this.dt
this.fpsBuffer.pop()
this.fpsBuffer.unshift(fps)
this.timestamp= timestamp this.timestamp= timestamp
this.tick(this.dt) this.tick(this.dt)
this.draw() this.draw()
@ -72,11 +79,12 @@ export default class Game {
drawFps(ctx) { drawFps(ctx) {
ctx.fillStyle = "white" ctx.fillStyle = "white"
ctx.fillRect(0, 0, 25, 20) ctx.fillRect(ctx.canvas.width, 0, -25, 20)
ctx.strokeStyle = "black" ctx.strokeStyle = "black"
ctx.textBaseline = "top" ctx.textBaseline = "top"
ctx.textAlign = "right"
ctx.font = "bold 20px serif" ctx.font = "bold 20px serif"
ctx.fillText(Math.round(1000 / this.dt), 0, 0) ctx.fillText(Math.round(average(this.fpsBuffer)), ctx.canvas.width, 0)
ctx.strokeText(Math.round(1000 / this.dt), 0, 0) ctx.strokeText(Math.round(average(this.fpsBuffer)), ctx.canvas.width, 0)
} }
} }

View File

@ -14,8 +14,17 @@ const doLengthsOverlap = (l1, l2) => {
return !((l1.x + l1.width < l2.x) || (l2.x + l2.width) < l1.x) return !((l1.x + l1.width < l2.x) || (l2.x + l2.width) < l1.x)
} }
function sum(array) {
return array.reduce((a, b) => a + b, 0)
}
function average(array) {
return sum(array) / array.length
}
export { export {
SQRT_OF_TWO, SQRT_OF_TWO,
isZeroVector, isZeroVector,
doRectanglesOverlap doRectanglesOverlap,
sum, average
} }