title: Show webcam / camera stream with delay - webrtc
body: <p>I've made a simple setup, getting the webcam / phone camera stream and the passing it on , drawing on a html 2d canvas.</p>
  
  <p>But ive been having trouble figuring out how to show the stream with a delay of few seconds. Kinda like a delay mirror. </p>
  
  <p>I tried playing with <code>ctx.globalAlpha = 0.005;</code> but this gives me a ghosting effect rather than 'delaying' the stream.</p>
  
  <p>Any idea how this can be achieved?</p>
  
  <ul>
  <li>The snippet below doesnt work here probably because of security issues apparently but here's a pen:</li>
  </ul>
  
  <p><a href="https://codepen.io/farisk/pen/LvmGGQ" rel="nofollow noreferrer">https://codepen.io/farisk/pen/LvmGGQ</a></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>  var width = 0, height = 0;
    
    var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d');
    document.body.appendChild(canvas);
    
    var video = document.createElement('video'),
        track;
    video.setAttribute('autoplay',true);
    
    window.vid = video;
    
    function getWebcam(){ 
    
      navigator.mediaDevices.getUserMedia({ video: true }).then(function(stream) {
   
  
        var videoTracks = stream.getVideoTracks();
        var newStream = new MediaStream(stream.getVideoTracks());
  
        video.srcObject = newStream;
        video.play();
        track = stream.getTracks()[0];
  
      }, function(e) {
        console.error('Rejected!', e);
      });
    }
    
    getWebcam();
    
    var rotation = 0,
        loopFrame,
        centerX,
        centerY,
        twoPI = Math.PI * 2;
    
    function loop(){
      
      loopFrame = requestAnimationFrame(loop);
          
      // ctx.globalAlpha = 0.005;
      ctx.drawImage(video, 0, 0, width, height);
      ctx.restore();
  
    }
    
    function startLoop(){ 
      loopFrame = requestAnimationFrame(loop);
    }
    
    video.addEventListener('loadedmetadata',function(){
      width = canvas.width = video.videoWidth;
      height = canvas.height = video.videoHeight;
      centerX = width / 2;
      centerY = height / 2;
      startLoop();
    });
    
    canvas.addEventListener('click',function(){
      if ( track ) {
        if ( track.stop ) { track.stop(); }
        track = null;
      } else {
        getWebcam();
      }
    });
    </code></pre>
  <pre class="snippet-code-css lang-css prettyprint-override"><code>video,
  canvas {
    max-width: 100%;
    height: auto;
  }</code></pre>
  </div>
  </div>
  </p>
  
  <ul>
  <li>The snippet below doesnt work here probably because of security issues apparently but here's a pen:</li>
  </ul>
  
  <p><a href="https://codepen.io/farisk/pen/LvmGGQ" rel="nofollow noreferrer">https://codepen.io/farisk/pen/LvmGGQ</a></p>