Crop dynamically part of video to paint to canvas

by Thanos Saringelos

HTML

<div style='position:relative;'>
  <canvas id="canvas" width=300 height=300></canvas>
  <video id='video' autoplay style='z-index : 0;'></video>
</div>
<div id='cc'>
  <canvas id='c'></canvas>
</div>
<video id='v'></video>

CSS

body {
  background-color: ivory;
}

#canvas {
  cursor:crosshair;
  border: 1px solid red;
  z-index: 2;
  position: absolute;
}

#video {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;
}
#cc {
  border: 1px solid black;
  position: relative;
}

JavaScript

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;
var video = document.querySelector('video');
// get references to the canvas and context
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var ratio=1;

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);
      //document.getElementById("v").src = window.URL.createObjectURL(stream);
      video.onloadedmetadata = function(e) {

        disW = video.videoWidth / factor;
        ratio = video.videoHeight / video.videoWidth;
        disH = disW * ratio;

        video.width = disW;
        video.play();
				//document.getElementById("v").play();
        
        canvas.width = disW;
        canvas.height = disH;
         
        document.getElementById('cc').style.width = disW + 'px';
        document.getElementById('cc').style.height = disW * ratio + 'px';
        document.getElementById('cc').style.top = (disW * ratio) + 'px';
        
        render();
       
      };
    },
    function(err) {
      console.log("The following error occured: " + err.name);
    }
  );
} else {
  console.log("getUserMedia not supported");
}



// calculate where the canvas is on the window
// (used to help calculate mouseX/mouseY)
var $canvas = $("#canvas");
var canvasOffset = $canvas.offset();
var offsetX = canvasOffset.left;
var offsetY = canvasOffset.top;
var scrollX = $canvas.scrollLeft();
var scrollY = $canvas.scrollTop();

// this flage is true when the user is dragging the mouse
var isDown = false;

//...