Javascript Question

Using webcam with Javascript to take snapshots

making a page to take snapshots with the webcam. but suddenly it stopped working on every computer. Did i make a typo i cant see myself, or does anyone has an idea too fix this??


  • added the draw in bit aswell

    // Put event listeners into place
    window.addEventListener("DOMContentLoaded", function() {
    // Grab elements, create settings, etc.
    var canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d"),
    video = document.getElementById("video"),
    videoObj = { "video": true },
    image_format= "jpeg",
    jpeg_quality= 85,
    errBack = function(error) {
    console.log("Video capture error: ", error.code);
    };


    // Put video listeners into place
    if(navigator.getUserMedia) { // Standard
    navigator.getUserMedia(videoObj, function(stream) {
    video.src = stream;
    video.play();
    $("#snap").show();
    }, errBack);
    } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
    navigator.webkitGetUserMedia(videoObj, function(stream){
    video.src = window.URL.createObjectURL(stream);
    video.play();
    $("#snap").show();
    }, errBack);
    } else if(navigator.mozGetUserMedia) { // moz-prefixed
    navigator.mozGetUserMedia(videoObj, function(stream){
    video.src = window.URL.createObjectURL(stream);
    video.play();
    $("#snap").show();
    }, errBack);
    }



    // Get-Save Snapshot - image
    document.getElementById("snap").addEventListener("click", function() {
    context.drawImage(video, 0, 0, 640, 480);
    // the fade only works on firefox?
    $("#video").fadeOut("slow");
    $("#canvas").fadeIn("slow");
    $("#snap").hide();
    $("#reset").show();
    $("#upload").show();


Answer

You never draw your video to the canvas in this part of the code.

Also, navigator.getUserMedia is not the "standard" anymore, it has been updated to navigator.mediaDevices.getUserMedia which will return a Promise.

var ctx = c.getContext('2d');
var vid = document.createElement('video');

vid.oncanplay = function() {
  c.width = this.videoWidth;
  c.height = this.videoHeight;
  draw();
}

navigator.mediaDevices.getUserMedia({
  video: true
}).then((stream) => {
  vid.srcObject = stream;
  vid.play();
});

function draw() {
  ctx.drawImage(vid, 0, 0);
  requestAnimationFrame(draw);
}
<canvas id="c"></canvas>

And a fiddle for chrome since it doesn't allow gUM in SO-snippets.

Ps : if you need to support older implementations, check the official WebRTC polyfill, adapter.js

Comments