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

相关推荐
m0_587383007 小时前
折扣卡CPS系统源码的技术架构与实战开发指南
人工智能·小程序·数据挖掘·系统架构·需求分析
2501_915106327 小时前
苹果App Store上架费用及流程全面解析
android·ios·小程序·https·uni-app·iphone·webview
T011561812 小时前
全栈项目实战手记|艺培场馆课时预约小程序全项目开发历程完整复盘总结
运维·服务器·小程序
lhldsg12 小时前
多商户团购系统源码:技术架构选型与二次开发实战指南
java·小程序·架构
2601_9499506313 小时前
一套小程序,解决资料整理、在线刷题和错题复盘
人工智能·小程序·刷题·练习·小程序推荐
白远山15 小时前
智慧场馆解决方案小程序系统开发实战与架构设计指南
java·开发语言·小程序·架构
Rooting++1 天前
小程序{{ }}和vue{{ }}语法的区别
前端·vue.js·小程序
博、、1 天前
折扣卡CPS系统源码实战开发指南:从架构设计到落地部署全解析
小程序·需求分析
lhldsg2 天前
折扣卡CPS小程序定制全流程实战指南:从需求分析到上线部署
java·前端·小程序
suliqiang2 天前
【前端技术】 Web 前端技术36年 演进全景图
信息可视化·微信小程序·小程序·前端框架·uni-app·人机交互·xcode