我尝试在网络浏览器上从网络摄像头拍摄快照。当我在下面使用此代码时,它适用于移动设备(Android上的Google Chrome),但不适用于桌面设备上的Google Chrome。视频未显示。我收到错误名称:TrackStartError
或DevicesNotFoundError
。它使用外部USB网络摄像头进行了测试。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Display Webcam Stream</title>
<style>
#container {
margin: 0 auto;
max-width: 480px;
}
video, img {
max-width: 100%;
background-color: #f2f3f5;
}
video {
height: 400px;
}
</style>
</head>
<body>
<div id="container">
<video autoplay></video>
</div>
<script>
var video = document.querySelector('video'), canvas;
function takeSnapshot() {
var img = document.querySelector('img') || document.createElement('img');
var context;
var width = video.offsetWidth, height = video.offsetHeight;
canvas = canvas || document.createElement('canvas');
canvas.width = width;
canvas.height = height;
context = canvas.getContext('2d');
context.drawImage(video, 0, 0, width, height);
img.src = canvas.toDataURL('image/png');
document.body.appendChild(img);
}
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function (constraints) {
var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
if (!getUserMedia) {
return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
}
return new Promise(function (resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
}
}
var constraints = {audio: false, video: {width: 640, height: 480}};
navigator.mediaDevices.getUserMedia(constraints)
.then(function (stream) {
if ("srcObject" in video) {
video.srcObject = stream;
} else {
video.src = window.URL.createObjectURL(stream);
}
video.onloadedmetadata = function (e) {
video.play();
};
video.addEventListener('click', takeSnapshot);
})
.catch(function (err) {
console.log(err.name + ": " + err.message);
});
</script>
</body>
</html>
&#13;
我没有任何选择:( 我做错了什么?它应该适用于大多数使用过的桌面Web浏览器。
答案 0 :(得分:0)
尝试一下(仅适用于视频):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta content="stuff, to, help, search, engines, not" name="keywords">
<meta content="What this page is about." name="description">
<meta content="Display Webcam Stream" name="title">
<title>Display Webcam Stream</title>
<style>
#container {
margin: 0px auto;
width: 500px;
height: 375px;
border: 10px #333 solid;
}
#videoElement {
width: 500px;
height: 375px;
background-color: #666;
}
</style>
</head>
<body>
<div id="container">
<video autoplay="true" id="videoElement">
</video>
</div>
<script>
var video = document.querySelector("#videoElement");
if (navigator.mediaDevices.getUserMedia) {
navigator.mediaDevices.getUserMedia({video: true})
.then(function(stream) {
video.srcObject = stream;
})
.catch(function(err0r) {
console.log("Something went wrong!");
});
}
</script>
</body>
</html>
参考:https://www.kirupa.com/html5/accessing_your_webcam_in_html5.htm