在html5中使用网络摄像头拍摄单张照片

时间:2015-07-23 19:19:56

标签: javascript jquery html5 navigator

我正在javascript中创建一个小类,使用网络摄像头进行电子和圆形应用。他们需要像数码相机一样使用相机,如图所示,查看视频流,单击按钮,然后保存该图像。

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);
      }
    });
  }
}

这将允许我创建一个流并将流作为视频元素附加到页面。但是,我的问题是:如何从这个流中获取单张图片?例如,在某种按钮上单击,保存当前帧。

$('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 */ );
});

如何在事件中以javascript格式保存视频流中的图片?

1 个答案:

答案 0 :(得分:1)

根据@putvande提供的链接,我可以在课堂上创建以下内容。我在构造函数中添加了一个画布以使其工作。抱歉,对于长代码块。

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;
  }
}