draw full camera stream video to canvas

draw full camera stream video to canvas

by Thanos Saringelos

HTML

<div style='position:relative;'> 
  <div class="containe2r">
      <div class="container" style='z-index : 10;'>
          <div class="column1">
             <canvas id="panel" style="border:1px solid red"> </canvas>     
          </div>  
      <div style="clear:both;"></div>  
      </div>

      <div id='dd' style='z-index : 0;'>
          <video autoplay style='z-index : 0;'></video>
      </div>
  </div> 
</div>
<div id='cc'>
  <canvas id='c'></canvas>
</div>

CSS

.containe2r{
  position:relative;
} 
.container{
  z-index : 10;
  position:absolute;
}
#dd { 
  position : absolute;
  top:0; 
  z-index : 0;
}
#cc{
  border:1px solid black;
  position:relative; 
}

JavaScript

var video = document.querySelector('video');
  var canvas = document.querySelector('canvas');
  var ctx = canvas.getContext('2d'); 
  
  var canvasC = document.getElementById('c'); 
	var ctx2 = canvasC.getContext('2d');
  var disW;
  var disH;
	var sourceX=1;
	var sourceY=1;
	var sourceWidth=1;
	var sourceHeight=1;
	var destX=1;
	var destY=1;
	var destWidth=1;
	var destHeight=1;
  var factor = 3;
    
  navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;

  window.URL = window.URL || window.webkitURL;
 
if (navigator.getUserMedia) {
    navigator.getUserMedia({ video: true,audio:true},
      function(stream) {
         video.src = window.URL.createObjectURL(stream);
         video.onloadedmetadata = function(e) {
         
         		disW = video.videoWidth/factor; 
            var ratio = video.videoHeight/video.videoWidth;
             disH = disW*ratio;
             
         		video.width = disW;  
            video.play();
             
            document.getElementById('panel').width = disW;
            document.getElementById('panel').height = disW*ratio;
            
            canvasC.width = disW;
            canvasC.height = disW*ratio;
            document.getElementById('cc').style.width = disW+'px';
            document.getElementById('cc').style.height = disW*ratio+'px';
             document.getElementById('cc').style.top = (disW*ratio)+'px';
             displayWidth = disW;
             displayHeight = disW*ratio;
            
            ctx2.drawImage(
              video,
              0,
              0,
              video.videoWidth,
              video.videoHeight,
              0,
              0,
              disW,
              displayHeight
            );
         };
      },
      function(err) {
         console.log("The following error occured: " + err.name);
      }
   );
} else {
   console.log("getUserMedia not supported");
}