注意:手机端只能在https连接下才能申请摄像头权限
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
video {
width: 100%;
height: 100%;
margin: 50px auto;
background-color: aquamarine;
display: block;
}
</style>
</head>
<body>
<video autoplay id="video"></video>
<script>
let video = document.getElementById('video');
function hasGetUserMedia() {
return !!(navigator.mediaDevices && navigator.mediaDevices.getUserMedia);
}
if (hasGetUserMedia()) {
const constraints = {
//video: { 'facingMode': "user" },//前置摄像头(手机默认)
video: { facingMode: { exact: "environment" }},//后置摄像头
};
const video = document.querySelector("video");
navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
console.log(stream)
video.srcObject = stream;
});
} else {
alert("getUserMedia() is not supported by your browser");
}
</script>
</body>
</html>
|