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

相关推荐
毕设源码-朱学姐13 小时前
【开题答辩全过程】以 基于微信小程序的大学生安全素质综合培养平台设计与实现为例,包含答辩的问题和答案
微信小程序·小程序
潆润千川科技15 小时前
中老年垂直社交小程序产品功能对比与设计思路分析
小程序
木风未来16 小时前
解锁自然新可能:露营租赁小程序如何让轻量化户外触手可及
小程序
木风未来19 小时前
破解家政维修信任困局:一个小程序如何让家庭服务更透明、更高效
小程序
Java.慈祥21 小时前
速通-微信小程序 5Day
java·微信小程序·小程序·npm
说私域21 小时前
数字围城下的防御与突围:基于私域流量与智能名片商城小程序的用户关系重构研究
小程序·重构·流量运营·私域运营
未来之窗软件服务1 天前
服务器运维(三十四)小程序web访问慢ssl优化—东方仙盟
运维·服务器·小程序·仙盟创梦ide·东方仙盟
全栈小51 天前
【小程序】微信小程序slice方法分割无效,单独输出一直为空,这是为什么呢
微信小程序·小程序·数组分割
Light601 天前
心智有效性测试小程序 V1.0 产品白皮书——心智结构量化与系统稳定性评估平台
小程序·apache
说私域1 天前
数字商超的崛起:基于“链动2+1模式智能名片S2B2C商城小程序”的社交电商生态重构
人工智能·小程序·重构·流量运营