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

相关推荐
脑袋大大的15 分钟前
钉钉小程序开发环境配置与前端开发指南
小程序·钉钉·企业应用开发
2301_805962933 小时前
微信小程序控制空调之接收MQTT消息
微信小程序·小程序·esp32
The_era_achievs_hero3 小时前
微信小程序121~130
微信小程序·小程序
難釋懷3 小时前
微信小程序WXSS 模板样式
微信小程序·小程序·notepad++
清颖~3 小时前
原生微信小程序研发,如何对图片进行统一管理?
微信小程序·小程序
默魔9 小时前
uniapp 微信小程序点击开始倒计时
微信小程序·小程序·uni-app
阿俊-全栈开发20 小时前
crmeb多门店对接拉卡拉支付小程序聚合收银台集成全流程详解
小程序·php·拉卡拉聚合收银台·拉卡拉三方支付
難釋懷1 天前
微信小程序全局配置
微信小程序·小程序
Enti7c1 天前
微信小程序核心知识点速览
微信小程序·小程序
2501_915918412 天前
Fiddler中文版全面评测:功能亮点、使用场景与中文网资源整合指南
android·ios·小程序·https·uni-app·iphone·webview