Canvas FPS Meter

In this example below you will see how to do a Canvas FPS Meter with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by mephysto, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright mephysto ©

Technologies

  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>Canvas FPS Meter</title>
  
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">

  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

  
<div class="container">
  <pre id="log">Oh hai world</pre>
  <canvas id="canvas"></canvas>
</div>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/mephysto/canvas-fps-meter-OELPoW */
body {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}

.container {
  width: 600px;
  height: 500px;
  background: mediumpurple;
}


/*Downloaded from https://www.codeseek.co/mephysto/canvas-fps-meter-OELPoW */
const log = document.getElementById('log')
const canvas = document.getElementById('canvas')
canvas.width = 600;
canvas.height = 500;
const ctx = canvas.getContext('2d')
const image = new Image();
image.src = 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/159368/alice-back.jpg'

const times = [];
let fps;


const calcPerf = () => {
  const now = performance.now();
  while (times.length > 0 && times[0] <= now - 1000) {
    times.shift();
  }
  times.push(now);
  fps = times.length;
  log.innerHTML = `${fps} FPS`
}

const draw = () => {
  // do some more fancy stuff here to test perf impact
  ctx.drawImage(image, 0,0)
}

const ticker = () => {
  window.requestAnimationFrame(() => {
    calcPerf();
    draw();
    ticker();
  });
}

ticker();

Comments