getUserMedia 获取 摄像头 拍照 代码 1920-1080 video canvas
20210422
摄像头代码 是基于 https 协议的,需要开启协议后才能测试
http-server -S 开启 https 服务
https://www.cnblogs.com/pengchenggang/p/14685560.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>摄像头拍照</title>
</head>
<body>
<video id="video" width="480" height="320"></video>
<div> <button id="capture">拍照</button> </div>
<video id="videoBig" width="1920" height="1080" style="display: none;"></video>
<canvas id="canvas" width="1920" height="1080" style="display: none;"></canvas>
<script>
//访问用户媒体设备的兼容方法
function getUserMedia(constraints, success, error) {
if (navigator.mediaDevices.getUserMedia) {
//最新的标准API
navigator.mediaDevices.getUserMedia(constraints).then(success).catch(error);
} else if (navigator.webkitGetUserMedia) {
//webkit核心浏览器
navigator.webkitGetUserMedia(constraints, success, error)
} else if (navigator.mozGetUserMedia) {
//firfox浏览器
navigator.mozGetUserMedia(constraints, success, error);
} else if (navigator.getUserMedia) {
//旧版API
navigator.getUserMedia(constraints, success, error);
}
}
var video = document.getElementById('video');
var videoBig = document.getElementById('videoBig');
var canvas = document.getElementById('canvas');
var context = canvas.getContext('2d');
function success(stream) {
//兼容webkit核心浏览器
var CompatibleURL = window.URL || window.webkitURL;
//将视频流设置为video元素的源
console.log(stream);
//video.src = CompatibleURL.createObjectURL(stream);
video.srcObject = stream;
video.play();
videoBig.srcObject = stream;
videoBig.play()
}
function error(error) {
console.log(`访问用户媒体设备失败${error.name}, ${error.message}`);
}
// jsp 调用拍照后的函数
function snapGetBase64(base64) {
console.info('snapGetBase64 - image Base64: ', base64)
}
function main() {
if (navigator.mediaDevices.getUserMedia || navigator.getUserMedia || navigator.webkitGetUserMedia || navigator
.mozGetUserMedia) {
//调用用户媒体设备, 访问摄像头
getUserMedia({
video: {
1920,
height: 1080
}
}, success, error);
} else {
alert('不支持访问用户媒体');
}
document.getElementById('capture').addEventListener('click', function () {
context.drawImage(videoBig, 0, 0, 1920, 1080);
var image = canvas.toDataURL('image/jpeg', 0.8)
snapGetBase64(image)
})
}
main();
</script>
</body>
</html>