【发布时间】:2017-01-25 15:28:23
【问题描述】:
我正在尝试使用 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);
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="debug.js"></script>
</head>
<body onload="init()">
<div id="mainContainer">
<video id="myVideo" width="640" height="480" autoplay style="display: inline;"></video>
<canvas id="myCanvas" width="640" height="480" style="display: inline;"></canvas>
<input type="button" id="snapshotButton" value="Snapshot" onclick="snapshot()"/>
</div>
</body>
</html>
问题是,我不想使用按钮单击来拍摄快照,而是在相机流加载后立即拍摄快照。 我尝试设置视频源后直接调用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);
}
但它不起作用。我的画布保持白色。我想这是因为此时相机流尚未完全加载。
那么是否有任何其他事件被触发,我可以在加载相机源后立即使用它来绘制快照?还是我完全走错了路?
提前致谢!
【问题讨论】:
-
你能把myVideo的快照打印出来吗?
-
当我在 snapshot() 函数中记录 myVideo 时,它会显示:
<video id="myVideo" width="640" height="480" autoplay="" style="display: inline;" src="blob:https://localhost:8081/317a70de-e87d-442a-bde7-cb4c75db01f3"></video> -
也许看看这个问题会有所帮助:stackoverflow.com/questions/12256668/…
-
这篇文章是关于错误的视频格式,但它让我走上了正轨:-)视频元素有一个“播放”-EventListener,所以我可以使用
myVideo.addEventListener('play', function(){ snapshot(); }, false);})非常感谢很多!