1.了解jsQR
jsQR是一个纯javascript脚本实现的二维码识别库,不仅可以在浏览器端使用,而且支持后端node.js环境。jsQR使用较为简单,有着不错的识别率。
2.效果图
3.二维码
4.下载jsqr
包
npm i -d jsqr
5.代码
<script setup>
import { ref } from 'vue'
import jsQR from "jsqr";const codeVal = ref('');function 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识别出来console.log('识别前的数据',imageData.data, imageData.width, imageData.height,
);const decodedResult = jsQR(imageData.data, imageData.width, imageData.height, {inversionAttempts: 'dontInvert',});if (decodedResult) {//返回识别结果return decodedResult.data} else {window.alert('未识别到二维码!')return ''}
}function upload() {let input = document.querySelector('#input')const file = input.files[0]console.log('文件是什么',file);if (file) {const reader = new FileReader();reader.onload = (e) => {const image = new Image();image.src = e.target.result;image.onload = () => {let code = decodeQRCode(image);console.log(code)//识别结果 codeVal.value = code;};};reader.readAsDataURL(file);}
}</script><template><!-- <button @click="$refs.input.click()">识别</button> --><input type="file" id="input" ref="input" @change="upload"><div>识别结果:{{codeVal}}</div><!-- <input type="file" style="display: none" id="input" @input="upload"> -->
</template>