<!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>js开启摄像头拍照并上传图片</title>
</head>
<body>
<video id="video" width="640" height="480" autoplay="autoplay"></video>
<canvas id="canvas" style="display: none;" width="640" height="480"></canvas>
<button onclick="openMedia()">开启摄像头</button>
<button id="capture" onclick="takePhoto()">拍照</button>
<button onclick="closeMedia()">关闭摄像头</button>
<div><img id="imgTag" src="" alt="imgTag"></div>
<script>
let video = document.getElementById("video");
let canvas = document.getElementById("canvas");
let context = canvas.getContext("2d");
function openMedia() {
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function (constraints) {
var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
if (!getUserMedia) {
return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
}
return new Promise(function (resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
}
}
let constraints = {video: true};
navigator.mediaDevices.getUserMedia(constraints)
.then(function (stream) {
if ("srcObject" in video) {
video.srcObject = stream;
} else {
video.src = window.URL.createObjectURL(stream);
}
video.onloadedmetadata = function (e) {
video.play();
};
})
.catch(function (err) {
console.log(err.name + ": " + err.message);
});
}
function takePhoto() {
context.drawImage(video, 0, 0, 640, 480);
let img = document.getElementById('canvas').toDataURL();
console.log('img-----', img);
document.getElementById('imgTag').src=img;
}
function closeMedia() {
if("srcObject" in video) {
let stream = video.srcObject;
let tracks = stream.getTracks();
tracks.forEach(function(track) {
track.stop();
});
video.srcObject = null;
}
}
</script>
</body>
</html>
参考:
https://www.cnblogs.com/cangqinglang/p/10210826.html