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

相关推荐
StarChainTech1 小时前
无人机租赁平台:开启智能租赁新时代
大数据·人工智能·微信小程序·小程序·无人机·软件需求
计算机毕设指导61 小时前
基于微信小程序的运动场馆服务系统【源码文末联系】
java·spring boot·微信小程序·小程序·tomcat·maven·intellij-idea
码农客栈2 小时前
小程序学习(十一)之uni-app和原生小程序开发区别
学习·小程序·uni-app
说私域2 小时前
基于AI客服链动2+1模式商城小程序的社群运营策略研究——以千人社群活跃度提升为例
人工智能·微信·小程序·私域运营
mqjFKmYf3 小时前
VSC整流系统定功率控制系统的MATLAB仿真模型(支持MATLAB 2014a及以上版本)
小程序
Json____3 小时前
使用uni-app开发抖音小程序遇到previewImage方法图片加载不出来解决方案
小程序·uni-app
毕设源码-钟学长4 小时前
【开题答辩全过程】以 基于微信小程序教学评价平台的设计与实现为例,包含答辩的问题和答案
微信小程序·小程序
说私域4 小时前
基于AI智能名片链动2+1模式S2B2C商城小程序的流量运营策略研究
人工智能·微信·小程序·产品运营·流量运营
阿巴资源站5 小时前
小程序原生授权手机号
小程序·apache
UI设计兰亭妙微5 小时前
兰亭妙微:以交互设计与UI设计赋能文旅小程序,重塑用户体验界面设计优化新标杆
小程序·ui设计外包