如何在javascript中直接从视频捕获转到数据URL?我想将图像显示为调整大小的版本,但保持全尺寸图像可用。那么,我该怎么做呢?
var PhotoBooth = {
onMediaStream: function(stream) {
PhotoBooth.canvas = $('canvas')[0];
PhotoBooth.context = PhotoBooth.canvas.getContext('2d');
PhotoBooth.localVideo = $('video')[0];
PhotoBooth.localVideo.src = window.URL.createObjectURL(stream);
},
noStream: function() {
console.log('FAIL TO GET WEBCAM ACCESS');
}
};
getUserMedia(
{video: true},
PhotoBooth.onMediaStream,
PhotoBooth.noStream
);
这是我目前保存图像以供上传的方式:
PhotoBooth.context.drawImage(PhotoBooth.localVideo, 0, 0, 200, 150);
$('#preview').show();
然后我像这样检索保存的图像:
var dataUrl = PhotoBooth.canvas.toDataURL();
我想保持画布与默认大小相同,但保留实际数据。基本上,我希望画布显示重新调整大小的版本,但保持完整大小的版本。
在这里,canvas
维护原始的 640x480 快照(使用 https fiddle for Chrome):
var start = () => navigator.mediaDevices.getUserMedia({ video: true })
.then(stream => video.srcObject = stream)
.catch(log);
var canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 480;
var snap = () => {
canvas.getContext('2d').drawImage(video, 0, 0, 640, 480);
preview.getContext('2d').drawImage(canvas, 0, 0, 160, 120);
}
var log = msg => div.innerHTML += "<br>" + msg;
<button onclick="start()">Start!</button>
<button onclick="snap()">Snap!</button><div id="div"></div>
<video id="video" width="160" height="120" autoplay></video>
<canvas id="preview" width="160" height="120"></canvas>