my-qrcode.js 2.1 KB
import QR from '../../utils/qrcode'

let app = getApp();
Page({
  data: {
    authorizeVisible: false,
    userInfo: {},
    qrImagePath: "",
  },
  onShareAppMessage() {},
  showAuth() {
    this.setData({
      authorizeVisible: true
    })
  },
  onLoad(options) {
    this.initData();
  },
  initData() {
    this.queryMember().then((result) => {

    });
  },
  /**
   * 获取会员信息
   */
  queryMember() {
    return new Promise((resolve, reject) => {
      app.post({
        url: app.api.member,
        data: {}
      }).then((result) => {
        let userInfo = result
        this.setData({
          userInfo
        })

        let tlMemberCode = userInfo.memberCode;
        // 设置二维码
        let qrSize = this.setCanvasSize(440);
        let codeContent = `tlMemberCode=${tlMemberCode}`
        this.createQrCode(codeContent, 'qrcanvas', qrSize.w, qrSize.h);

        resolve();
      })
    });
  },

  createQrCode(content, canvasId, cavW, cavH) {
    //调用插件中的draw方法,绘制二维码图片
    QR.api.draw(content, canvasId, cavW, cavH);
    this.canvasToTempImage(canvasId);
  },
  //获取临时缓存图片路径,存入data中
  canvasToTempImage(canvasId) {
    let that = this;
    wx.canvasToTempFilePath({
      canvasId, // 这里canvasId即之前创建的canvas-id
      success: function (res) {
        let tempFilePath = res.tempFilePath;
        console.log(tempFilePath);
        that.setData({ // 如果采用mpvue,即 this.imagePath = tempFilePath
          qrImagePath: tempFilePath,
        });
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
  //适配不同屏幕大小的canvas
  setCanvasSize(sz) {
    var size = {};
    try {
      var res = wx.getSystemInfoSync();
      var scale = 750 / sz; //不同屏幕下canvas的适配比例;设计稿是750宽
      var width = res.windowWidth / scale;
      var height = width; //canvas画布为正方形
      size.w = width;
      size.h = height;
    } catch (e) {
      // Do something when catch error
      console.log("获取设备信息失败" + e);
    }
    return size;
  },

})