在网页中调用电脑摄像头拍照
下面的测试代码必须放在服务器上面,且域名必须是https
时才能正常调用摄像头!
<!doctype html>
<html lang="en">
<head>
<title>拍照</title>
<meta charset="utf-8">
<style>
.capture-info {
color: #e6a23c;
font-size: 14px;
}
.capture-video-box {
background-color: #000;
margin: 10px 0;
width: 418px;
height: 418px;
}
#capture-video {
display: none;
}
.capture-box {
width: 432px;
}
.capture-canvas-box {
width: 86px;
height: 86px;
border: 1px solid #CCC;
margin-bottom: 10px;
}
.button{
display: inline-block;
line-height: 1;
white-space: nowrap;
cursor: pointer;
border: 1px solid #409eff;
color: #fff;
background-color: #409eff;
-webkit-appearance: none;
text-align: center;
box-sizing: border-box;
outline: none;
margin: 0;
transition: .1s;
font-weight: 500;
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
padding: 12px 20px;
font-size: 14px;
border-radius: 4px;
}
.capture-open{
position: absolute;
top: 209px;
left: 170px;
}
</style>
</head>
<body>
<div class="capture-box">
<div class="capture-info">提示: 该功能需要使用你的电脑摄像头拍照,点击下方按钮开启</div>
<div class="capture-video-box">
<div class="capture-open button" id="capture-open-button" onclick="getMedia()">开启摄像头</div>
<video id="capture-video" width="418px" height="418px" autoplay="autoplay"></video>
</div>
<div class="capture-canvas-box">
<canvas id="capture-canvas" width="86px" height="86px"></canvas>
</div>
<div>
<button class="button" onclick="takePhoto()">拍照</button>
<button class="button">上传</button>
</div>
</div>
<script>
//获得video摄像头区域
let video = document.getElementById("capture-video");
var isInit = false;
function getMedia() {
let constraints = {
video: { width: 418, height: 418 },
audio: false
};
/*
新的方法:H5新媒体接口 navigator.mediaDevices.getUserMedia()
这个方法会提示用户是否允许媒体输入,(媒体输入主要包括相机,视频采集设备,屏幕共享服务,麦克风,A/D转换器等)
返回的是一个Promise对象。
如果用户同意使用权限,则会将 MediaStream对象作为resolve()的参数传给then()
如果用户拒绝使用权限,或者请求的媒体资源不可用,则会将 PermissionDeniedError作为reject()的参数传给catch()
*/
try{
let promise = navigator.mediaDevices.getUserMedia(constraints);
promise.then(function (MediaStream) {
video.style.display = 'block';
video.srcObject = MediaStream;
video.play();
isInit = true;
document.getElementById("capture-video").style.display = 'none';
}).catch(function (PermissionDeniedError) {
console.log(PermissionDeniedError);
})
}catch (e) {
alert('开启摄像头失败');
}
}
function takePhoto() {
if(isInit === false){
alert('摄像头未开启,无法拍照');
return false;
}
//获得Canvas对象
let canvas = document.getElementById("capture-canvas");
let ctx = canvas.getContext('2d');
ctx.drawImage(video, 0, 0, 86, 86);
var photoSrc = document.getElementById("capture-canvas").toDataURL("image/jpeg", 0.8);
console.log(photoSrc, 12121)
}
</script>
</body>
</html>
文章来源:
鸿辰
版权声明:本网站可能会转载或引用其他来源的文章、图片、数据等信息。对于这些转载内容,版权归原作者所有。本站尊重原作者的劳动成果,并在可能的情况下注明来源和作者。如有任何版权问题,请及时联系,收到后将第一时间处理。