gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 14:45:04 25 4
gpt4 key购买 nike

我正在用 javascript 制作一个小类,将网络摄像头用于电子和 cylon 应用程序。他们需要像使用数码相机一样使用相机,例如查看视频流、单击按钮并保存该图像。

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 提供的链接,我能够在类里面创建以下内容。我向构造函数添加了一个 Canvas 以使其工作。抱歉,代码块太长了。

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

关于javascript - 在 html5 中使用网络摄像头拍摄单张照片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31596290/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com