小程序解析二维码: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不行,如果有可以的请分享一下

相关推荐
技术闲聊DD17 小时前
小程序原生-利用setData()对不同类型的数据进行增删改
小程序
康康爹17 小时前
uniapp 小程序,登录上传头像昵称页面处理步骤
小程序·uni-app
小雨cc5566ru17 小时前
小程序 uniapp+Android+hbuilderx体育场地预约管理系统的设计与实现
android·小程序·uni-app
DK七七1 天前
【PHP陪玩系统源码】游戏陪玩系统app,陪玩小程序优势
前端·vue.js·游戏·小程序·php·uniapp
正小安1 天前
MobX-Miniprogram:微信小程序的状态管理利器
微信小程序·小程序
GDAL1 天前
软考鸭微信小程序:助力软考备考的便捷工具
微信小程序·小程序
技术闲聊DD1 天前
小程序原生-列表渲染
小程序
2401_844137952 天前
JAVA智慧社区系统跑腿家政本地生活商城系统小程序源码
微信·微信小程序·小程序·生活·微信公众平台·微信开放平台
程序员入门进阶2 天前
4S店4S店客户管理系统小程序(lw+演示+源码+运行)
小程序
光影少年2 天前
Vue Mini基于 Vue 3 的小程序框架
前端·vue.js·小程序