参考HTML5Rocks 上的这篇文章,我正在尝试构建一个实用程序来从网络摄像头拍照。
下面是我的 HTML 代码片段:
<button type="button" name="btnCapture" id="btnCapture">Start my camera</button><br />
<video autoplay="true" id="video" style="height:240px;width:320px"></video><canvas id="canvas" style="display: none; height:240px;width:320px"></canvas><br />
<img id="capturedImage" src="/blank.gif" style="height:240px;width:320px"><input type="hidden" id="hdnImageBase64" name="hdnImageBase64"><br />
单击按钮后,btnCapture
我启动网络摄像头并再次单击它它从网络摄像头捕获照片并将其放入图像capturedImage
中。
下面是我的 JavaScript 代码:
var video = document.getElementById("video");
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var localMediaStream = null;
var capturedImage = document.getElementById("capturedImage");
var buttonTextCapturePicture = "Say Cheese!";
function onFailSoHard(e) {
if (e.code == 1) {
alert("Something went wrong! Either your webcam is not connected or you denied access to it.");
} else {
alert("getUserMedia() not supported in your browser. Try using latest version of Google Chrome or Opera.");
}
}
function snapshot() {
if (localMediaStream) {
try {
ctx.drawImage(video, 0, 0);
capturedImage.src = canvas.toDataURL("image/png");
document.getElementById("hdnImageBase64").value = canvas.toDataURL("image/png");
} catch (e) {
alert("Something went wrong while capturing you. Try refreshing the page. " + e);
}
}
}
video.addEventListener("click", snapshot, false);
function sizeCanvas() {
setTimeout( function() {
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
capturedImage.height = video.videoHeight;
capturedImage.width = video.videoWidth;
}, 50);
}
var button = document.getElementById("btnCapture");
button.addEventListener("click", function(e) {
if (localMediaStream) {
snapshot();
return;
}
if (navigator.getUserMedia) {
navigator.getUserMedia("video", function(stream) {
video.src = stream;
localMediaStream = stream;
sizeCanvas();
button.textContent = buttonTextCapturePicture;
}, onFailSoHard);
} else if (navigator.webkitGetUserMedia) {
navigator.webkitGetUserMedia({"video" : true}, function(stream) {
video.src = window.webkitURL.createObjectURL(stream);
localMediaStream = stream;
sizeCanvas();
button.textContent = buttonTextCapturePicture;
}, onFailSoHard);
} else {
onFailSoHard({
target : video
});
}
}, false);
当btnCapture
第一次单击按钮时,它会调用函数sizeCanvas()
将画布和图像宽度和高度设置为视频的宽度和高度(即 320 和 240)。当第二次单击该按钮时,它会使用来自网络摄像头的 Base64 编码快照canvas.toDataURL
并将其放入 imagecapturedImage
中。
它适用于 Opera。但在谷歌浏览器中,第一次加载页面时总是失败。但是当刷新同一页面时,它可以工作。尝试调试时,我发现代码第一次canvas.toDataURL
返回图像 Base64 data:,
,因此无法绘制图像,导致Resource interpreted as Image but transferred with MIME type text/plain: "data:,".
控制台出错。此外,如果我不调用该函数sizeCanvas
,那么它会第一次工作,但图片不是我需要的尺寸并被裁剪。
有什么想法可以让我第一次在 Chrome 中使用它sizeCanvas
吗?
谷歌浏览器:24.0.1312.57 歌剧:12.11