使用html5的网络摄像头拍摄一张照片

Take a single picture using webcam in html5

本文关键字:一张照片 摄像头 网络 html5 使用      更新时间:2023-09-26

我正在制作一个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上的事件?

基于@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;
  }
}