html部分:
< html lang=“en”>
< head>
< title>GET VIDEO</ title>
< meta name=“viewport” content=“width=device-width” />
< script src=“js/jquery-1.11.3.min.js”></ script>
</ head>
< body>
< video id=“video” class=“vio” autoplay=“autoplay”></ video>
< canvas id=“canvas” width=“200px” height=“100px”></ canvas>
< img src="" id=“img” />
< input type=“button” title=“视频” value=“视频” οnclick=“getVedio();” />< br />
< script>
var img = document.getElementById(“img”);
window.onload = function() {
let constraints = {
video: {
width: 200,
height: 200
},
};
/**
* 录像展示的位置
/
let video = document.getElementById(“video”);
let promise = navigator.mediaDevices.getUserMedia(constraints);
promise.then((MediaStream) => {
/*
* MediaStream 返回参数
* active: true
* id: “ykCZTVor0KNVypRFZW8dFSwrFd9QuihhWmqA”
* onactive: null
* onaddtrack: null
* oninactive: null
* onremovetrack: null
*/
console.info(MediaStream);
video.srcObject = MediaStream;
video.play();
}).catch((error) => {
alert(“未检测到摄像头,请连接设备!”)
console.info(error);
});
getVedio=function(){
let canvas = document.getElementById("canvas");
canvas.getContext('2d').drawImage(video, 0, 0, 200, 100);
/**
* 拿到图片的base64
* canvas base64
*/
canvas = canvas.toDataURL("image/png");
/**
* 拍照以后将video元素移除
* 拍照将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 {
}
}
}
/**
* 将图片转为file格式{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
});
}
/**
* base64位图片转码文件流
* param {type}
* Date: 2019-05-25 09:57:22
*/
base64toFile = function (dataurl, filename = 'file') {
let arr = dataurl.split(',')
let mime = arr[0].match(/:(.*?);/)[1]
let suffix = mime.split('/')[1]
let bstr = atob(arr[1])
let n = bstr.length
let u8arr = new Uint8Array(n)
while (n--) {
u8arr[n] = bstr.charCodeAt(n)
}
return new File([u8arr], `${filename}.${suffix}`, {
type: mime
})
}
// {Object} theBlob 文件 {Object} fileName 文件名字
blobToFile = function(theBlob, fileName) {
theBlob.lastModifiedDate = new Date();
theBlob.name = fileName;
return theBlob;
}
//调用
</script>
</ body>
</ html>
此处使用的是标签实现的
navigator.mediaDevices.getUserMedia(constraints);调起摄像头
通过 MediaDevices.getUserMedia() 获取用户多媒体权限时,需要注意其只工作于以下三种环境:
localhost 域
开启了 HTTPS 的域
使用 file:/// 协议打开的本地文件
因此本地测试可以直接使用,部署在服务器上需要将应用部署成https的才可以支持