自学内容网 自学内容网

小程序解析二维码:jsQR

1.了解jsQR

jsQR是一个纯javascript脚本实现的二维码识别库,不仅可以在浏览器端使用,而且支持后端node.js环境。jsQR使用较为简单,有着不错的识别率。

2.效果图

请添加图片描述

3.二维码

在这里插入图片描述

4.下载jsqr

npm i -d jsqr

5.代码

<!-- 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>
// 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不行,如果有可以的请分享一下


原文地址:https://blog.csdn.net/weixin_47124112/article/details/137550864

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!