开箱即用
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>拍照</title>
<script src="https://cdn.bootcss.com/vConsole/3.3.4/vconsole.min.js"></script>
<script>
var vConsole = new VConsole();
console.log("Hello world");
</script>
<style>
*{
margin: 0;
padding: 0;
}
.loading {
display: flex;
}
dot {
height: 1em;
line-height: 1;
display: flex;
flex-direction: column;
overflow: hidden;
}
dot::before {
content: "...\A..\A.";
white-space: pre-wrap;
animation: dot 3s infinite step-end;
}
.src-video{
width: 400px;
height: 400px;
object-fit: cover;
}
.photo {
width: 100%;
height: 100%;
object-fit: scale-down;
}
@keyframes dot {
0% {
transform: translateY(-3em);
}
50% {
transform: translateY(-1em);
}
100% {
transform: translateY(0em);
}
}
</style>
</head>
<body>
<span class="loading">正在加载中<dot>...</dot> </span>
<button onclick="reversal()">反转</button>
<button onclick="closeMedia()">关闭摄像头</button>
<button onclick="openMedia()">开启摄像头</button>
<button onclick="takePhoto()">拍照</button><br /><br />
<video class="src-video" autoplay playsinline></video>
<div class="img-box" style="display: none;">
<img src="" alt="" class="photo" />
</div>
</body>
<script>
let srcVideo = document.querySelector("video.src-video");
let mediaStream;
let photo = document.querySelector("img.photo");
let imgbox = document.querySelector("div.img-box");
let front = true
let openMedia = async function () {
photo.src = "";
let constraints = {
audio: false,
video: {
facingMode: front ? 'user' : 'environment',
},
};
const mediaPromise =
window.navigator.mediaDevices.getUserMedia(constraints);
console.log(navigator.mediaDevices);
const isWx = /micromessenger/i.test(navigator.userAgent)
const isComWx = /wxwork/i.test(navigator.userAgent);
console.log(isComWx);
console.log(isWx);
await mediaPromise
.then(function (stream) {
mediaStream = stream;
srcVideo.srcObject = stream;
srcVideo.onloadedmetadata = async () => {
await srcVideo.play();
};
})
.catch(function (err) {
alert(err);
});
};
let takePhoto = function () {
const width = srcVideo.videoWidth
const height = srcVideo.videoHeight
const canvas = document.createElement('canvas')
canvas.width = width
canvas.height = height
let ctx = canvas.getContext("2d");
ctx.drawImage(srcVideo, 0, 0, width, height);
srcVideo.style.display = 'none'
photo.src = canvas.toDataURL()
imgbox.style.display = 'block'
};
let closeMedia = function () {
return new Promise(reslove => {
mediaStream.getTracks().forEach(async(track) => {
await track.stop();
});
reslove()
})
};
let reversal = function () {
closeMedia().then(() => {
front = ! front
openMedia()
})
}
</script>
</html>
以上就是使用getUserMedia调用摄像头拍照的所有代码了 欢迎各位大佬指点