簡體   English   中英

在html5中使用網絡攝像頭拍攝一張照片

[英]Take a single picture using webcam in html5

我正在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;
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM