我正在尝试使用navigator.mediaDevices.getUserMedia()
和canvas.getContext('2d').drawImage()
函数从网络摄像头拍摄快照。
当我这样做时,它可以完美地工作:
function init(){
myVideo = document.getElementById("myVideo")
myCanvas = document.getElementById("myCanvas");
videoWidth = myCanvas.width;
videoHeight = myCanvas.height;
startVideoStream();
}
function startVideoStream(){
navigator.mediaDevices.getUserMedia({audio: false, video: { width: videoWidth, height: videoHeight }}).then(function(stream) {
myVideo.src = URL.createObjectURL(stream);
}).catch(function(err) {
console.log("Unable to get video stream: " + err);
});
}
function snapshot(){
myCanvas.getContext('2d').drawImage(myVideo, 0, 0, videoWidth, videoHeight);
}
问题是,我不想使用按钮单击来拍摄快照,而是在相机流加载后立即拍摄快照。设置视频源后,我尝试直接调用snapshot()函数:
function init(){
myVideo = document.getElementById("myVideo")
myCanvas = document.getElementById("myCanvas");
videoWidth = myCanvas.width;
videoHeight = myCanvas.height;
startVideoStream();
}
function startVideoStream(){
navigator.mediaDevices.getUserMedia({audio: false, video: { width: videoWidth, height: videoHeight }}).then(function(stream) {
myVideo.src = URL.createObjectURL(stream);
snapshot();
}).catch(function(err) {
console.log("Unable to get video stream: " + err);
});
}
function snapshot(){
myCanvas.getContext('2d').drawImage(myVideo, 0, 0, videoWidth, videoHeight);
}
但这是行不通的。我的画布保持白色。我想这是因为相机流此时尚未完全加载。
那么,是否还有其他事件被触发,一旦加载了相机供稿,我就可以使用它来绘制快照?还是我完全走错了轨道?
提前致谢!