调摄像头功能请在线上环境测试,本地http无法调取摄像头
html:
src="../../assets/img/ocr.svg"
class="icon_border" />
js:
showDialog() {
let constraints = {
video: { width: 300, height: 300, facingMode: "user" },
audio: true
};
// facingMode: "user" 这个配置是调前置摄像头
let _this = this;
_this.$nextTick(() => {
_this.thisVideo = document.getElementById("videoCamera");
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function(constraints) {
var getUserMedia =
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.getUserMedia;
if (!getUserMedia) {
return Promise.reject(
new Error("getUserMedia is not implemented in this browser")
);
}
return new Promise(function(resolve, reject) {
getUserMedia.call(navigator, constraints, resolve, reject);
});
};
}
navigator.mediaDevices
.getUserMedia(constraints)
.then(function(stream) {
_this.MediaStreamTrack =
typeof stream.stop === "function"
? stream
: stream.getTracks()[0];
if ("srcObject" in _this.thisVideo) {
_this.thisVideo.srcObject = stream;
} else {
_this.thisVideo.src = window.URL.createObjectURL(stream);
}
_this.thisVideo.onloadedmetadata = function(e) {
_this.thisVideo.play();
_this.trackImg();
};
})
.catch(err => {
Toast({
closeOnClickOverlay: true,
duration: 0,
forbidClick: true,
message: JSON.stringify(err)
});
});
});
}
trackImg() {
let that = this;
let count = 0;
that.tracker = new tracking.ObjectTracker("face");
that.tracker.setInitialScale(2);
that.tracker.setStepSize(1.1);
that.tracker.setEdgesDensity(0.1);
tracking.track("#videoCamera", that.tracker);
that.tracker.on("track", function(event) {
if (event.data.length === 0) {
that.title = "请按照提示上传您的头像";
// 没有检测到人脸时执行
} else {
// 有检测到人脸时执行
event.data.forEach(function(rect) {
that.trackArea(rect.x, rect.y, rect.width, rect.height);
});
}
});
// 检测到人脸时在页面实时打标记
trackArea(x, y, w, h) {
let img = this.$refs.tip_area;
img.style.position = "absolute";
img.style.width = w + "px";
img.style.height = h + "px";
img.style.left = x + "px";
img.style.top = y + "px";
}
以上方法在安卓上有效:ios暂不支持此方法调摄像头
ios上通过input调摄像功能,监听onchange事件获取视频流,代码参考如下:
function videoChange() {
var file = document.getElementById('video-input').files[0];
var fileSize = (Math.round(file.size / 1024)).toFixed();
document.getElementById('info').innerHTML += "所录视频大小约为:" + (fileSize / 1024).toFixed(2) + "Mb";
var url = URL.createObjectURL(file);
console.log(url);
document.getElementById("video").src = url;
}