Canvas FPS Example
by rsmclaug
HTML
<span id="second-fps"></span>
<canvas id="my-canvas" width="100" height="100"></canvas>
CSS
canvas {
background: #414141;
}
#second-fps {
position: absolute;
top: 110px;
}
JavaScript
var fps = 0,
lastRun = new Date().getTime(),
sixtyFrameCounter = 0,
canvas = document.getElementById("my-canvas"),
context = canvas.getContext("2d");
context.fillStyle = "white";
context.font = "16pt Arial";
function gameLoop(){
var delta = (new Date().getTime() - lastRun) / 1000;
lastRun = new Date().getTime();
fps = 1 / delta;
//Clear screen
context.clearRect(0, 0, 100, 100);
context.fillText(fps.toFixed(0) + " FPS", 10, 26);
//Print FPS every 60 frames
if (sixtyFrameCounter === 60) {
$("#second-fps").text(fps.toFixed(0) + " FPS at " + new Date());
sixtyFrameCounter = 0;
}
sixtyFrameCounter++;
requestAnimationFrame(gameLoop);
}
gameLoop();