H5调用摄像头
页面展示
playsInline
控制视频是否在网页内直接播放
<video
id="video"
width="100px"
height="75px"
playsInline
></video>
<canvas id="canvas" v-show="false"></canvas>
使用 getUserMedia
调用摄像头
发现问题: video标签播放后,发现视频镜像
// 调用摄像头
openMedia() {
navigator.mediaDevices.getUserMedia(this.myConstraints).then(
(stream) => {
//播放视频
video.srcObject = stream;
video.play();
},
(error) => {
console.error(error.name || error);
}
);
},
利用 canvas
截取摄像内容
发现问题: 截取后的图片也是镜像(已解决)
// 截取摄像内容
screen() {
var canvas = document.getElementById("canvas");
var video = document.getElementById("video");
var ctx = canvas.getContext("2d");
console.log(video.videoWidth, video.videoHeight);
var width = video.videoWidth;
var height = video.videoHeight;
canvas.width = width;
canvas.height = height;
ctx.translate(width, 0); // 解决截屏镜像
ctx.scale(-1, 1); // 解决截屏镜像
ctx.drawImage(video, 0, 0, width, height);
var url = canvas.toDataURL("image/png");
const blobImage = this.dataURLtoBlob(url);
let fileName = `${this.$store.getters.user.nickName}_${this.parseTime(
new Date()
)}.jpg`;
const fileOfBlob = new File([blobImage], fileName);
// 下载
// const aDom = document.createElement("a");
// aDom.download = fileOfBlob.name;
// let href = URL.createObjectURL(fileOfBlob);
// aDom.href = href;
// document.body.appendChild(aDom);
// aDom.click(); // 触发 a 标签的点击
// document.body.removeChild(aDom);
// URL.revokeObjectURL(href);
// 上传图片到服务器
// let formData = new FormData();
// formData.append("file", fileOfBlob, fileName);
// uploadScreen(formData).then((response) => {
// this.imgList.push(response.fileName);
// });
},
// 转换成图片方法
dataURLtoBlob(dataUrl) {
let 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,
});
},
解决镜像问题
#video {
transform: rotateY(180deg);
-webkit-transform: rotateY(180deg); /* Safari 和 Chrome */
-moz-transform: rotateY(180deg);
}