赞
踩
jsQR
jsQR是一个纯javascript脚本实现的二维码识别库,不仅可以在浏览器端使用,而且支持后端node.js环境。jsQR使用较为简单,有着不错的识别率。
jsqr
包npm i -d jsqr
<!-- index.wxml -->
<view class="container">
<button bindtap="chooseImage">选择图片识别二维码</button>
<canvas id="qrcodeCanvas" canvas-id="qrcodeCanvas" style="width: {{canvasWidth}}px; height: {{canvasHeight}}px"></canvas>
</view>
<button bind:tap="process">识别</button>
<button style="width: 100vw; margin-top: 20rpx;">识别结果:{{msg}}</button>
// index.js import jsQR from "jsqr"; Page({ data: { msg: "", canvasWidth: 0, canvasHeight: 0, }, chooseImage() { wx.vibrateShort(); wx.chooseMedia({ count: 1, mediaType: ["image"], sourceType: ["album", "camera"], success: (res) => { this.decodeQRCode(res.tempFiles[0].tempFilePath); }, fail: (err) => { console.error("选择图片失败", err); }, }); }, decodeQRCode(imagePath) { wx.getImageInfo({ src: imagePath, success: (imageInfo) => { this.setData({ canvasWidth: imageInfo.width, canvasHeight: imageInfo.height, }); const canvasId = "qrcodeCanvas"; const ctx = wx.createCanvasContext(canvasId); ctx.drawImage(imagePath, 0, 0, imageInfo.width, imageInfo.height); ctx.draw(); }, fail: (err) => { console.error("获取图片信息失败", err); }, }); }, process() { const imageInfo = { width: this.data.canvasWidth, height: this.data.canvasHeight, }; wx.canvasGetImageData({ canvasId: "qrcodeCanvas", x: 0, y: 0, width: imageInfo.width, height: imageInfo.height, success: (res) => { console.log(res); const imageData = { data: res.data, width: imageInfo.width, height: imageInfo.height, }; // console.log( // "识别前的数据", // imageData.data, // imageData.width, // imageData.height // ); const decodedResult = jsQR( imageData.data, imageData.width, imageData.height, { inversionAttempts: "dontInvert", } ); console.log("结果", decodedResult); if (decodedResult) { console.log(decodedResult.data); // 识别结果 this.setData({ msg: decodedResult.data, }); } else { wx.showToast({ icon: "none", title: "未识别到二维码!", }); } }, fail: (err) => { console.error("获取 Canvas 像素数据失败", err); }, }); }, });
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。