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;;
    }, errBack);
    } else if(navigator.webkitGetUserMedia) { // WebKit-prefixed
    navigator.webkitGetUserMedia(videoObj, function(stream){
    video.src = window.URL.createObjectURL(stream);;
    }, errBack);
    } else if(navigator.mozGetUserMedia) { // moz-prefixed
    navigator.mozGetUserMedia(videoObj, function(stream){
    video.src = window.URL.createObjectURL(stream);;
    }, errBack);

    // Get-Save Snapshot - image
    document.getElementById("snap").addEventListener("click", function() {
    context.drawImage(video, 0, 0, 640, 480);
    // the fade only works on firefox?

Answer Source

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;

  video: true
}).then((stream) => {
  vid.srcObject = stream;;

function draw() {
  ctx.drawImage(vid, 0, 0);
<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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download