嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):813200300
本次赞助数额为: 3 元微信扫码支付:3 元
请留下您的邮箱,我们将在2小时内将文件发到您的邮箱
安卓,华为荣耀平板自带浏览器亲测H5页面调用摄像头扫码识别成功,测试项目源码完整下载。
****注意电脑端浏览器不可用,请用IIS部署,用平板或者安卓手机测试。
请在https的协议下运行,否则部分浏览器可能会报错:请在安全的浏览器下运行
<script>
function log(msg) {
$("#log").append(msg "<br/>");
}
var videoInputDevice = [];
var videoElement = document.getElementById("QRvideo");
var canvasElement = document.getElementById("qr-canvas");
var canvasContext = document.getElementById("qr-canvas").getContext("2d");
var canvasTimer = null;
var decodeTimer = null;
function captureToCanvas() {
try {
// 根据视频大小设置canvas大小
let w = videoElement.videoWidth;
let h = videoElement.videoHeight;
canvasElement.width = w;
canvasElement.height = h;
canvasContext.drawImage(videoElement, 0, 0, w, h);
} catch (e) {
//log(e);
};
// 100毫秒绘制一次
canvasTimer = setTimeout(captureToCanvas, 100);
}
function decode() {
try {
qrcode.decode();
} catch (e) {
//log(e);
};
// 100毫秒绘制一次
decodeTimer = setTimeout(decode, 100);
}
//扫码识别完成
qrcode.callback = (e) => {
// 清除画布,停止摄像头
if (!!decodeTimer) clearTimeout(decodeTimer);
if (!!canvasTimer) clearTimeout(canvasTimer);
canvasContext.clearRect(0, 0, 300, 400);
if (window.stream) {
window.stream.getTracks().forEach((track) => {
track.stop();
});
}
$.colorbox.close();
log("得到扫码结果:" e);
}
//获取摄像头列表
navigator.mediaDevices.enumerateDevices().then(function(devices) {
for (let i = 0; i !== devices.length; i) {
let deviceInfo = devices[i];
//log(deviceInfo.kind ":" deviceInfo.label "; id = " deviceInfo.deviceId)
if (deviceInfo.kind === 'videoinput') {
// 视频设备
videoInputDevice.push(deviceInfo);
}
}
});
//开始扫码
document.querySelector('#scan').addEventListener('click', () => {
try {
//显示拍照框
$.colorbox({
scrolling: false,
reposition: true,
inline: true,
href: "#divQRScan"
});
//开启摄像头
navigator.mediaDevices.getUserMedia({
audio: false,
video: {
deviceId: {
// [1].deviceId 表示后置摄像头,默认开启的是前置摄像头
exact: videoInputDevice[1].deviceId
}
}
}).then(function(stream) {
window.stream = stream;
videoElement.srcObject = stream;
videoElement.play();
captureToCanvas();
decode();
}).catch(function(error) {
$.colorbox.close();
if (error.toString().indexOf("TypeError: Cannot read property 'deviceId' of undefined") != -1) {
alert("无法访问摄像头!请授予手机浏览器摄像头权限或切换至有摄像头权限的浏览器!");
} else {
log(error.toString());
}
});
canvasContext.clearRect(0, 0, 300, 400);
} catch (e) {
log(e);
}
});
</script>