requestAnimationFrame

MAKE SURE TO CLICK INTO THE RESULT IFRAME OR ELSE SAFARI WILL ONLY RENDER RAF / SETINTERVAL AT MAX 30FPS DUE TO POWER SAVING CODE

by dustinkerstein

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>

CSS

body {
  margin: 0;
  padding: 0;
  background-color: black; 
}

video {
  width: 100vw;
  height: 100vh;
}

JavaScript

var url = "https://files.panomoments.com/smpte.mp4";
var video = document.createElement('video');
var frameCount = 0;
var frameRate = 1;
var direction = 1;
video.muted = true;
video.loop = true;
/* video.controls = true; */
document.body.appendChild(video);
window.requestAnimationFrame(render)

function render() {
  window.requestAnimationFrame(render);
  frameCount++;
  direction = (frameCount % 400 < 200) ? 1 * frameRate: -1 * frameRate;
  if (video.readyState >= 2) {
  	var newTime = (video.currentTime + (1 / direction)) % video.duration;
    if (newTime <= 0 && direction == -1) {
    	video.currentTime = video.duration;
    } else if (newTime >= video.duration && direction == -1) {
    	video.currentTime = video.duration;
    } else if (newTime <= 0 && direction == 1) {
    	video.currentTime = 0;
    } else if (newTime >= video.duration && direction == 1) {
    	video.currentTime = 0;
    } else {
    	video.currentTime = newTime;
    }
  }
}

fetch(url).then(function(response) {
  response.blob().then(function(blob) {
    video.src = window.URL.createObjectURL(blob);
  });
});