WebRTC webcam example

by BaguetteSeeker

HTML

<video id="video"></video>
<button id="startbutton">Take photo</button>
<canvas id="canvas"></canvas>
<img src="http://placekitten.com/g/200/150" id="photo" alt="photo">

CSS

html {
    background: #111111;
    height: 100%;
    background: linear-gradient( #333, #000);
}
canvas {
    display: none;
}
video, img, #startbutton {
    display: block;
    float: left;
    border: 10px solid #fff;
    border-radius: 10px;
}
#startbutton {
    background: green;
    border: none;
    color: #fff;
    margin: 100px 20px 20px 20px;
    padding: 10px 20px;
    font-size: 20px;
}
#container {
    overflow: hidden;
    width: 880px;
    margin: 20px auto;
}

JavaScript

(function() {

  var streaming = false,
      video        = document.querySelector('#video'),
      cover        = document.querySelector('#cover'),
      canvas       = document.querySelector('#canvas'),
      photo        = document.querySelector('#photo'),
      startbutton  = document.querySelector('#startbutton'),
      width = 200,
      height = 0;

 navigator.mediaDevices
      .getUserMedia({ video: true, audio: false })
      .then((stream) => {
        video.srcObject = stream;
        video.play();
      })
      .catch((err) => {
        console.error(`An error occurred: ${err}`);
      });

  video.addEventListener('canplay', function(ev){
    if (!streaming) {
      height = video.videoHeight / (video.videoWidth/width);
      video.setAttribute('width', width);
      video.setAttribute('height', height);
      canvas.setAttribute('width', width);
      canvas.setAttribute('height', height);
      streaming = true;
    }
  }, false);

  function takepicture() {
    canvas.width = width;
    canvas.height = height;
    canvas.getContext('2d').drawImage(video, 0, 0, width, height);
    var data = canvas.toDataURL('image/png');
    photo.setAttribute('src', data);
  }

  startbutton.addEventListener('click', function(ev){
      takepicture();
    ev.preventDefault();
  }, false);

})();