我想使用 javascript 访问我的设备相机。但此代码仅适用于 firefox,也适用于桌面。我想在其他浏览器和移动设备上访问我的相机。
function start()
{
var video = document.getElementById('video'),
vendorUrl = window.URL;
navigator.mediaDevices.getUserMedia({
video: true,
audio: true
})
.then(function(stream) {
video.src = vendorUrl.createObjectURL(stream);
video.play();
})
.catch(function(err) {
alert("no");
});
};
最佳答案
(function() {
'use strict';
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) {
// access the web cam
navigator.mediaDevices.getUserMedia({video: true})
.then(function(stream) {
video.srcObject = stream
video.addEventListener('click', takeSnapshot);
})
.catch(function(error) {
document.body.textContent = 'Could not access the camera. Error: ' + error.name;
});
}
})();
video, img {
max-width:100%;
}
<video autoplay></video>
复制到本地运行
希望对你有帮助
关于javascript - 使用javascript访问设备相机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49473678/