Take a picture with a webcam in html5

I am making a small class in javascript to use a webcam for an electron and cylinder application. They have to use the camera like a digital camera, for example in a video stream, press a button and save this image.

class Camera {
  constructor() {
    this.video = document.createElement('video');
  }
  getStream() {
    return new Promise(function (resolve, reject) {
      navigator.webkitGetUserMedia({ video: true }, resolve, reject);
    });
  }
  streamTo(stream, element) {
    var video = this.video;
    return new Promise(function (resolve, reject) {
      element.appendChild(video);
      video.src = window.URL.createObjectURL(stream);
      video.onloadedmetadata = function (e) {
        video.play();
        resolve(video);
      }
    });
  }
}

      

This will allow me to create a stream and add the stream to the page as a video element. However, my question is, how can I get one picture from this stream? For example, on some button press, save the current frame.

$('button[data-action="take-picture"]').on('click', function (ev) {
  // the clicked button has a "source" referencing the video.
  var video = $(ev.target).data('source');
  // lost here. Want to catch current "state" of the video.
  // take that still image and put it in the "target" div to preview.
  $(ev.target).data('target').append( /** my image here */ );
});

      

How do I save an image from a video stream to javascript in an event?

+3


source to share


1 answer


Based on @putvande link I was able to create the following in my class. I added a canvas to the constructor to make it work. Sorry for the long block of code.



class Camera {
  constructor(video, canvas, height=320, width=320) {
    this.isStreaming = false;  // maintain the state of streaming
    this.height = height;
    this.width = width;

    // need a canvas and a video in order to make this work.
    this.canvas = canvas || $(document.createElement('canvas'));
    this.video = video || $(document.createElement('video'));
  }

  // streamTo and getStream are more or less the same.

  // returns a new image element with a still shot of the video as streaming.
  takePicture() {
    let image = new Image();
    let canv = this.canvas.get(0)
    var context = canv.getContext('2d');
    context.drawImage(this.video.get(0), 0, 0, this.width, this.height);
    var data = canv.toDataUrl('image/png');
    image.src = data;
    return image;
  }
}

      

+1


source







All Articles