ZXing,一个支持在图像中解码和生成条形码(如二维码、PDF 417、EAN、UPC、Aztec、Data Matrix、Codabar)的库。ZXing(“zebra crossing”)是一个开源的项目。支持多语言
GitHub地址:https://github.com/zxing/zxing
因为项目需求研究了下js的基本使用方法,直接上代码
window.addEventListener('load', function () {
// 老的浏览器可能根本没有实现 mediaDevices,所以我们可以先设置一个空的对象
if (navigator.mediaDevices === undefined) {
navigator.mediaDevices = {};
}
if (navigator.mediaDevices.getUserMedia === undefined) {
navigator.mediaDevices.getUserMedia = function (constraints) {
var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
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);
});
}
}
if (
navigator.mediaDevices != undefined &&
navigator.mediaDevices.getUserMedia != undefined
) {
const constraints = {
video: {
facingMode: "environment", //后置摄像头
width: 720, height: 1280, //可以调节宽度 超出范围有时候无法显示
// width: {
// min: 1280,
// ideal: 1920,
// max: 2560,
// },
// height: {
// min: 720,
// ideal: 1080,
// max: 1440,
// },
},
};
navigator.mediaDevices.getUserMedia(constraints).then(stream => {
const video = document.getElementById("video");
if ("srcObject" in video) {
video.srcObject = stream;
} else {
video.src = window.URL.createObjectURL(stream);
}
video.onloadedmetadata = function (e) {
video.play();
};
codeReaderFn();
}).catch(err => {
alert(err);
//document.getElementById('result2').textContent = err;
// reject(err);
})
}
})
function codeReaderFn() {
let selectedDeviceId;
const codeReader = new ZXing.BrowserMultiFormatReader()
// 获取摄像头列表
codeReader.listVideoInputDevices()
.then((videoInputDevices) => {
//const sourceSelect = document.getElementById('sourceSelect')
//document.getElementById('result2').textContent = selectedDeviceId;
if (videoInputDevices.length >= 1) {
// 遍历摄像头个数
videoInputDevices.forEach((element) => {
const sourceOption = document.createElement('option')
sourceOption.text = element.label
sourceOption.value = element.deviceId
if (element.label.indexOf('back') != -1) {
selectedDeviceId = element.deviceId;
} else {
selectedDeviceId = videoInputDevices[videoInputDevices.length - 1].deviceId
}
})
decodeFromVideoDevice(codeReader, selectedDeviceId, 'video');
}
})
.catch((err) => {
console.error(err)
})
}
function decodeFromVideoDevice(codeReader, selectedDeviceId, domId) {
codeReader.decodeFromVideoDevice(selectedDeviceId, domId, (result, err) => {
// 扫码结果回调
if (result) {
getGoods(result.text);
}
if (err && !(err instanceof ZXing.NotFoundException)) {
console.error(err);
}
})
}
Zxing项目非常大,按需引入
原创©本文章为闫志林原创,未经许可,禁止转载
0条评论