Select FPS to paint video on canvas

by Thanos Saringelos

HTML

<video id='video' muted hidden>
  <source id="mp4" src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">
</video>
<canvas id='canvas' width='854' height='480'></canvas>
<div id='log1'> 
</div>
<div id='log2'> 
</div>

CSS

#canvas {
   width: 213.5px;
   height: 120px;
 }

JavaScript

var fps = 30;
var now;
var then = Date.now();
var interval = 1000 / fps;
var delta;

var vid = document.getElementById('video');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
var startTimeRender = Date.now();
var startTimePainting = Date.now();
var paintTimes = 0;
var renderTimes = 0;
var timeLimit = 1000;

function draw() {

  requestAnimationFrame(draw);

  now = Date.now();
  delta = now - then;
 
  renderTimes++;
  
  // here we count how many times/secthe the draw function is called by the browser
  if (Date.now() - startTimeRender > timeLimit) {
   
   console.log("%cThe render() run " + renderTimes + " times the last " + (timeLimit / 1000) + " seconds.", "background: black; color: white; font-size: large"); 
    startTimeRender = Date.now();
    renderTimes = 0;
    
  } 
	
  // here we enter to if the right amount of times has passed, to actually execute meaningful paint stuff
  if (delta > interval) {

    paintTimes++;
     

    if (Date.now() - startTimePainting > timeLimit) {
    
     // here we count how many times/secthe the draw function is called by the browser
    console.log("%cThe canvases were rendered " + paintTimes + " times the last " + (timeLimit / 1000) + " seconds.", "background: black; color: white; ");
 
      startTimePainting = Date.now();
      paintTimes = 0;
    } 
     
    // Just `then = now` is not enough.
    // Lets say we set fps at 10 which means
    // each frame must take 100ms
    // Now frame executes in 16ms (60fps) so
    // the loop iterates 7 times (16*7 = 112ms) until
    // delta > interval === true
    // Eventually this lowers down the FPS as
    // 112*10 = 1120ms (NOT 1000ms).
    // So we have to get rid of that extra 12ms
    // by subtracting delta (112) % interval (100).
    // Hope that makes sense.

    then = now - (delta % interval);

    // ... Code for Drawing the Frame ...
    context.drawImage(video, 0, 0, 854, 480);
    
  }
}

video.onplaying =...