js调用后置摄像头拍照(若无则前置)
emer 发布于 2020-8-18 14:47 1547 次阅读
<canvas style="display:none;" id="canvas" width="2100" height="2800"></canvas>
callCamera(videoDom) {
if (!navigator.mediaDevices) {
return Promise.reject("浏览器不支持navigator.mediaDevices");
}
return navigator.mediaDevices.enumerateDevices().then(arr => {
let sources = arr
.filter(a => {
return a.kind.indexOf("video") > -1;
})
.map(a => {
return a.deviceId;
});
return navigator.mediaDevices
.getUserMedia({
video: {
deviceId: sources[1] || sources[0]
}
})
.then(stream => {
if ("srcObject" in videoDom) {
videoDom.srcObject = stream;
} else {
//避免在新的浏览器中使用它,因为它正在被弃用。
videoDom.src = window.URL.createObjectURL(stream);
}
videoDom.onloadedmetadata = function (e) {
videoDom.play();
};
});
});
},
var canvas = document.getElementById("canvas")
this.context = canvas.getContext("2d")
this.callCamera(document.getElementById('video')).catch(function (err) {
console.log(err.name + ": " + err.message);
});
// 点击,canvas画图
this.context.drawImage(video, 0, 0, 2100, 2800);
// 获取图片base64链接
var image = canvas.toDataURL('image/png',1.0);
// 定义一个img
var img = new Image();
//设置属性和src
img.id = "imgBoxxx";
img.src = image;
//将图片添加到页面中
// document.body.appendChild(img);
// base64转文件
function dataURLtoFile(dataurl, filename) {
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 File([u8arr], filename, {type: mime});
}
// console.log(dataURLtoFile(image, 'aa.png'));
var formdata = new FormData();
formdata.append('file', dataURLtoFile(image, 'aa.png'));
this.show1=true;
axios.post('/refresh', formdata, {
headers: {
'Content-Type': 'multipart/form-data',
},
}).then(res => {
//棒棒哒,你上传了
}
}).catch(err => {
console.log(err);
});
// xhr.open("POST", "/refresh", true);
// xhr.onreadystatechange = function () {
// if (xhr.readyState == 4 && xhr.status == 200) {
// }
// }
// xhr.send(formdata);
},