npm
npm i -d jsqr
html
<el-button @click="$refs.input.click()">识别</el-button>
<input type="file" style="display: none" id="input" @input="upload">
js
import jsQR from "jsqr";
decodeQRCode(image) {
//创建画布
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
canvas.width = image.width;
canvas.height = image.height;
//把二维码画上去
context.drawImage(image, 0, 0, canvas.width, canvas.height);
const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
//jsQR识别出来
const decodedResult = jsQR(imageData.data, imageData.width, imageData.height, {
inversionAttempts: 'dontInvert',
});
if (decodedResult) {
//返回识别结果
return decodedResult.data
} else {
window.alert('未识别到二维码!')
return ''
}
}
upload(){
let input = document.querySelector('#input')
const file = input.files[0]
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
const image = new Image();
image.src = e.target.result;
image.onload = () => {
let code = this.decodeQRCode(image);
console.log(code)//识别结果
};
};
reader.readAsDataURL(file);
}
}