首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在html5中使用网络摄像头拍摄单张照片

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

Stack Overflow用户
提问于 2015-07-24 03:19:56
回答 1查看 1.6K关注 0票数 3

我正在用javascript做一个小类,用于电子和cylon应用程序的摄像头。他们需要像使用数码相机一样使用相机,例如,查看视频流,单击按钮,然后保存图像。

代码语言: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);
      }
    });
  }
}

这将允许我制作一个流,并将流作为视频元素附加到页面。然而,我的问题是:我如何才能从这个流中获得单个图片?例如,在某种类型的按钮单击时,保存当前帧。

代码语言:javascript
复制
$('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保存视频流中的图片?

EN

回答 1

Stack Overflow用户

发布于 2015-07-24 22:47:43

基于提供的link @putvande,我能够在我的类中创建以下代码。我在构造函数中添加了一个画布以使其正常工作。很抱歉,代码块太长了。

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31596290

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档