使用 jsqr 解析二维码图片内容
npm install jsqr
<template> <div> <button type="primary" @click="handUpload">上传图片</button> <div style="display: none;"> <input type="file" accept="image/png, image/jpeg" ref="fileInput" @change="changeFile" /> <img id="myimg"> <canvas id="mycanvas"></canvas> </div> </div> </template>
import jsQR from "jsqr" handUpload() { this.$refs['fileInput'].click() }, // 解析二维码中的文本、上传图片是否是二维码 changeFile(e) { let fileReader = new FileReader(); fileReader.onload = function(event) { let data = event.target.result; let img = document.getElementById("myimg"); img.src = data; img.onload = function() { let mycanvas = document.getElementById("mycanvas"); let ctx = mycanvas.getContext("2d"); // canvas 的width/height重新设置的时候会清空画布 mycanvas.width = img.width; mycanvas.height = img.height; ctx.drawImage(img, 0, 0); let imageData = ctx.getImageData(0, 0, img.width, img.height); const code = jsQR(imageData.data, imageData.width, imageData.height); if(code) console.log("解析出来的文本:", code.data) else console.log("%c上传图片未识别到二维码", "color: #f00;") } } fileReader.readAsDataURL(e.target.files[0]); },
注:二维码最中心如果是微信图标时,将扫描不出来