小程序解析二维码:jsQR

1.了解jsQR

jsQR是一个纯javascript脚本实现的二维码识别库,不仅可以在浏览器端使用,而且支持后端node.js环境。jsQR使用较为简单,有着不错的识别率。

2.效果图

3.二维码

4.下载jsqr

bash 复制代码
npm i -d jsqr

5.代码

html 复制代码
<!-- 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>
js 复制代码
// index.js
import jsQR from "jsqr";

Page({
  data: {
    msg: "",
    canvasWidth: 0,
    canvasHeight: 0,
  },

  chooseImage() {
    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() {
    wx.canvasGetImageData({
      canvasId: "qrcodeCanvas",
      x: 0,
      y: 0,
      width: this.data.canvasWidth,
      height: this.data.canvasHeight,
      success: (res) => {
        console.log(res);
        const decodedResult = jsQR(
          res.data,
          this.data.canvasWidth,
          this.data.canvasHeight,
          {
            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);
      },
    });
  },
});

注意:我使用canvas2d不行,如果有可以的请分享一下

相关推荐
萧寂1732 小时前
微信小程序自定义轮播图指示点样式
微信小程序·小程序
R_yy11 小时前
微信小程序开发——视频播放实现(本地视频或者云端视频均可)
前端·微信小程序·小程序
低代码布道师15 小时前
加油站小程序实战教程03站点管理
低代码·小程序
V+zmm1013418 小时前
智慧物流小程序(论文源码调试讲解)
java·数据库·微信小程序·小程序·毕业设计
霍格沃兹测试开发学社测试人社区18 小时前
性能测试丨微信小程序性能优化指南
性能优化·微信小程序·小程序
猿毕设21 小时前
【FL0100】基于SSM微信小程序的走失人员的报备平台
java·spring boot·后端·python·微信小程序·小程序
猿毕设21 小时前
【FL0091】基于SSM和微信小程序的社区二手物品交易小程序
java·spring boot·后端·python·微信小程序·小程序
前端小雪的博客.1 天前
Uniapp 小程序复制、粘贴功能实现
小程序·uni-app
V+zmm101341 天前
岳阳市美术馆预约平台(小程序论文源码调试讲解)
java·数据库·微信小程序·小程序·毕业设计