1.html
<video
id="videoCamera"
:width="videoWidth"
:height="videoHeight"
autoplay
></video>
<canvas
style="display: none"
id="canvasCamera"
:width="videoWidth"
:height="videoHeight"
></canvas>
<div>
<p>照片</p>
<img :src="imgSrc"/>
</div>
2.打开摄像机方法
const videoWidth = 200;
const videoHeight = 200;
const imgSrc = ref("");
let thisCancas = null;
let thisContext = null;
let thisVideo = null;
const getCompetence = () => {
openVideo.value = true;
thisCancas = document.getElementById("canvasCamera");
thisContext = thisCancas.getContext("2d");
thisVideo = document.getElementById("videoCamera");
thisVideo.style.display = "block";
// 获取媒体属性,旧版本浏览器可能不支持mediaDevices,我们首先设置一个空对象
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
// 一些浏览器实现了部分mediaDevices,我们不能只分配一个对象
// 使用getUserMedia,因为它会覆盖现有的属性。
// 这里,如果缺少getUserMedia属性,就添加它。
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function (constraints) {
// 首先获取现存的getUserMedia(如果存在)
var getUserMedia =
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.getUserMedia;
// 有些浏览器不支持,会返回错误信息
// 保持接口一致
if (!getUserMedia) {
//不存在则报错
return Promise.reject(
new Error("getUserMedia is not implemented in this browser")
);
}
// 否则,使用Promise将调用包装到旧的navigator.getUserMedia
return new Promise(function (resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
};
}
var constraints = {
audio: false,
video: {
width: videoWidth,
height: videoHeight,
},
};
navigator.mediaDevices
.getUserMedia(constraints)
.then(function (stream) {
// 旧的浏览器可能没有srcObject
if ("srcObject" in thisVideo) {
thisVideo.srcObject = stream;
} else {
// 避免在新的浏览器中使用它,因为它正在被弃用。
thisVideo.src = window.URL.createObjectURL(stream);
}
thisVideo.onloadedmetadata = function (e) {
thisVideo.play();
};
})
.catch((err) => {
console.log(err);
});
};
// 绘制图片(拍照功能)
const setImage = () => {
var _this = this;
// canvas画图
thisContext.drawImage(thisVideo, 0, 0, videoWidth, videoHeight);
// 获取图片base64链接
var image = thisCancas.toDataURL("image/png");
imgSrc.value = image; //赋值并预览图片
};
3. 如果报错 getUserMedia is not implemented in this browser
- 使用 https 协议
- 客户端浏览器手动指定域名安全
- chrome://flags/#unsafely-treat-insecure-origin-as-secure
- 如果用iframe 嵌套 在标签上添加allow="camera;microphone"