Drop on purpose fps

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>

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;

  // stats for Auri
  renderTimes++;
  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;
  }
  // end of stats for Auri

  if (delta > interval) {
    // update time stuffs

    // stats for Auri
    paintTimes++;
    
    if (Date.now() - startTimePainting > timeLimit) {
      console.log("%cThe canvases were rendered "+paintTimes+" times the last "+(timeLimit/1000)+" seconds.", "background: black; color: white; ");

      startTimePainting = Date.now();
      paintTimes = 0;
    }
    // end of stats for Auri

    // 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 = function() {

  console.log(this.videoWidth)
  console.log(this.videoHeight)
  draw();

}
video.play();