今天简单的记录一个JS调取摄像头的源码,不是很难,只是为了以后可以直接拿来使用,好的废话不多说,看源码!
代码语言:javascript复制<!doctype html>
<html lang="en">
<head>
<title>GET VIDEO</title>
<meta charset="utf-8">
<script src="js/jquery.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<video id="video" class="vio" autoplay="autoplay"></video>
<!--隐藏掉 为了发送照片-->
<canvas id="canvas" width="200px" height="100px"></canvas>
<img src="" id="img" />
<script>
var img = document.getElementById("img");
window.onload = function() {
let constraints = {
video: {
width: 200,
height: 100
},
};
/**
* @desc 录像展示的位置
*/
let video = document.getElementById("video");
let promise = navigator.mediaDevices.getUserMedia(constraints);
promise.then((MediaStream) => {
/**
* @desc MediaStream 返回参数
* active: true
* id: "ykCZTVor0KNVypRFZW8dFSwrFd9QuihhWmqA"
* onactive: null
* onaddtrack: null
* oninactive: null
* onremovetrack: null
*/
console.info(MediaStream);
video.srcObject = MediaStream;
video.play();
}).catch((error) => {
console.info(error);
});
/**
* @desc 倒计时以后进行拍照的操作
*/
setTimeout(function() {
let canvas = document.getElementById("canvas");
canvas.getContext('2d').drawImage(video, 0, 0, 200, 100);
/**
* @desc 拿到图片的base64
* @param canvas base64
*/
canvas = canvas.toDataURL("image/png");
/**
* @desc 拍照以后将video元素移除
* @desc 拍照将base64转为file文件
*/
if(canvas) {
var m = document.getElementById("video");
m.parentNode.removeChild(m);
//document.getElementById('img').setAttribute('src', canvas);
//console.info(document.getElementById('img'));
var blob = dataURLtoBlob(canvas);
var file = blobToFile(blob, "imgName");
console.info(file);
} else {
}
}, 3000);
}
/**
* 将图片转为file格式
* @param {Object} dataurl 将拿到的base64的数据当做参数传递
*/
dataURLtoBlob = function(dataurl) {
var arr = dataurl.split(','),
mime = arr[0].match(/:(.*?);/)[1],
bstr = atob(arr[1]),
n = bstr.length,
u8arr = new Uint8Array(n);
while(n--) {
u8arr[n] = bstr.charCodeAt(n);
}
return new Blob([u8arr], {
type: mime
});
}
/**
*
* @param {Object} theBlob 文件
* @param {Object} fileName 文件名字
*/
blobToFile = function(theBlob, fileName) {
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}
//调用
</script>
</body>
</html>
上面的注释写的很明白,这里就不做过多的解释,直接可以运行的,