wxml

<view>
  <button bindtap='createQrcode' type="primary" style="width: 400rpx;margin-top: 400rpx;">生成二维码</button>
  <canvas id='qrcode' type="2d" style='width:300rpx;height:300rpx;margin-top: 30rpx;margin-left: 100rpx;' ></canvas>
</view>

js

// pages/hr/demo/demo.js
import QRCode from '../../../utils/weapp.qrcode.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    qrCodeLink: "2352425234234",
    qrcodePath: null

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {

  },
  // 生成二维码
createQrcode() {
  var that = this;
  const query = wx.createSelectorQuery()
  query.select('#qrcode')
    .fields({
      node: true,
      size: true
    })
    .exec((res) => {
      var canvas = res[0].node
 
      // 调用方法drawQrcode生成二维码
      QRCode({
        canvas: canvas,
        canvasId: 'qrcode',
        // width:that.createRpx2px(300),
        // width: that.createRpx2px(300),
        // padding: 10,
        // background: '#ffffff',
        // foreground: '#000000',
        text: that.data.qrCodeLink,
      })
 
      // 获取临时路径(得到之后,想干嘛就干嘛了)
      wx.canvasToTempFilePath({
        canvasId: 'qrcode',
        canvas: canvas,
        x: 0,
        y: 0,
        success(res) {
          // console.log('二维码临时路径:', res.tempFilePath)
          that.setData({
            qrcodePath: res.tempFilePath
          })
          console.log('二维码临时路径:', that.data.qrcodePath)
        },
        fail(res) {
          console.error(res)
        }
      })
    })
  },

})

下载weapp.qrcode.js地址:https://gitee.com/WeiDoctor/weapp-qrcode-canvas-2d,将代码下载下来后,获取utils目录下的js文件,

放到项目的util目录下

 3、效果如下:

 

posted on 2024-01-29 10:53  周文豪  阅读(27)  评论(0编辑  收藏  举报