14--微信小程序 二维码(组件)canvas

本文介绍如何在微信小程序中使用canvas组件生成二维码,并探讨相关回调函数的应用,帮助开发者实现二维码功能。
摘要由CSDN通过智能技术生成

在这里插入图片描述
页面:

<view class="container">
  <view class="header">
    <text class="code-tit">班级编号:</text>
    <text class="code-num">{
   {
   classid}}</text>
  </view>
  <view class="qrcode-box">
    <canvas class="canvas" style="width:{
   {qrcode_w}}px; height:{
   {qrcode_w}}px;" canvas-id="couponQrcode"></canvas>
  </view>
  <view class="btn">
    <button bindtap="save" class="save" type="submit" size="mini">保存</button>
  </view>
  <tui-icon class="close" name="shut" size="30" bindtap="close"></tui-icon>
</view>

js:

const qrCode = require('../../../utils/weapp-qrcode')

Component({
   
  properties: {
   
    classid: {
   
      type: String,
      value: ""
    }
  },

  data: {
   
    qrcode_w: 150
  },
  lifetimes: {
   
    attached: function() {
   
      let qrcode = this.couponQrcode(this.data.classid, 'couponQrcode')

      this.setData({
   
        qrcode
      })
      // Console.log(qrcode)
    }
  },

  methods: {
   
    couponQrcode(text, canvasId) {
   
      let qrcode = new qrCode(canvasId, {
   
        text: text,
        width: this.data.qrcode_w,
        height: this.data.qrcode_w,
        colorDark: "#333333",
        colorLight: "#ffffff",
        correctLevel: qrCode.CorrectLevel.H,
        usingIn: this
      });
      return qrcode
    },
    //关闭
    close: function() {
   
      this.triggerEvent('close', {
   })
    },
    //保存
    save:function() {
   
      this.data.qrcode.exportImage(function(res) {
   
        console.log(res)
        if (res.tempFilePath) {
   
          wx.saveImageToPhotosAlbum({
   
            filePath: res.tempFilePath,
            success: res => {
   

            }
          })
        } else {
   
          wx.showToast({
   
            title: res.errMsg,
            icon: "none"
          })
        }

      })
    } //save方法

  }, //methods 结束


})

样式:

.container {
   
  border: 1px solid #eaeaea;
  padding: 7px 59px;
  margin-top: 10px;
}

.header {
   
  text-align: center;
  margin-top: 6px;
}

.close {
   
  position: relative;
  bottom: 227px;
  left: 171px;
}
.qrcode-box{
   
  margin-top: 4px;
}
.canvas {
   
  margin: 0 auto;
  position: relative;
  top: 9px;
}

.btn {
   
  position: relative;
  left: 41px;
  top:23px;
}

.save {
   
  color: #fff;
  background-color: #298ef7;
  border: 1px solid #eaeaea;
}

json:

{
   
  "component": true,
  "usingComponents": {
   
    "tui-button": "/static/thorui/components/button/button",
    "tui-icon": "/static/thorui/components/icon/icon"
  }
}

引入在这里插入图片描述
引用组件必须加上这句。。!!! this._htOption.usingIn
下面代码已有。
在这里插入图片描述
回调
在这里插入图片描述
weapp-qrcode.js

//Core code comes from https://github.com/davidshimjs/qrcodejs

var QRCode;

(function() {
   
  /**
   * Get the type by string length
   * 
   * @private
   * @param {String} sText
   * @param {Number} nCorrectLevel
   * @return {Number} type
   */
  function _getTypeNumber(sText, nCorrectLevel) {
   
    var nType = 1;
    var length = _getUTF8Length(sText);

    for (var i = 0, len = QRCodeLimitLength.length; i <= len; i++) {
   
      var nLimit = 0;

      switch (nCorrectLevel) {
   
        case QRErrorCorrectLevel.L:
          nLimit = QRCodeLimitLength[i][0];
          break;
        case QRErrorCorrectLevel.M:
          nLimit = QRCodeLimitLength[i][1];
          break;
        case QRErrorCorrectLevel.Q:
          nLimit = QRCodeLimitLength[i][2];
          break;
        case QRErrorCorrectLevel.H:
          nLimit = QRCodeLimitLength[i][3];
          break;
      }

      if (length <= nLimit) {
   
        break;
      } else {
   
        nType++;
      }
    }

    if (nType > QRCodeLimitLength.length) {
   
      throw new Error("Too long data");
    }

    return nType;
  }

  function _getUTF8Length(sText) {
   
    var replacedText = encodeURI(sText).toString().replace(/\%[0-9a-fA-F]{
   2}/g, 'a');
    return replacedText.length + (replacedText.length != sText ? 3 : 0);
  }

  function QR8bitByte(data) {
   
    this.mode = QRMode.MODE_8BIT_BYTE;
    this.data = data;
    this.parsedData = [];

    // Added to support UTF-8 Characters
    for (var i = 0, l = this.data.length; i < l; i++) {
   
      var byteArray = [];
      var code = this.data.charCodeAt(i);

      if (code > 0x10000) {
   
        byteArray[0] = 0xF0 | ((code & 0x1C0000) >>> 18);
        byteArray[1] = 0x80 | ((code & 0x3F000) >>> 12);
        byteArray[2] = 0x80 | ((code & 0xFC0) >>> 6);
        byteArray[3] = 0x80 | (code & 0x3F);
      } else if (code > 0x800) {
   
        byteArray[0] = 0xE0 | ((code & 0xF000) >>> 12);
        byteArray[1] = 0x80 | ((code & 0xFC0) >>> 6);
        byteArray[2] = 0x80 | (code & 0x3F);
      } else if (code > 0x80) {
   
        byteArray[0] = 0xC0 | ((code & 0x7C0) >>> 6);
        byteArray[1] = 0x80 | (code & 0x3F);
      } else {
   
        byteArray[0] = code;
      }

      this.parsedData.push(byteArray);
    }

    this.parsedData = Array.prototype.concat.apply([], this.parsedData);

    if (this.parsedData.length != this.data.length) {
   
      this.parsedData.unshift(191);
      this.parsedData.unshift(187);
      this.parsedData.unshift(239);
    }
  }

  QR8bitByte.prototype = {
   
    getLength: function(buffer) {
   
      return this.parsedData.length;
    },
    write: function(buffer) {
   
      for (var i = 0, l = this.parsedData.length; i < l; i++) {
   
        buffer.put(this.parsedData[i], 8);
      }
    }
  };


  // QRCodeModel
  function QRCodeModel(typeNumber, errorCorrectLevel) {
   
    this.typeNumber = typeNumber;
    this.errorCorrectLevel = errorCorrectLevel;
    this.modules = null;
    this.moduleCount = 0;
    this.dataCache = null;
    this.dataList = [];
  }
  QRCodeModel.prototype = {
   
    addData: function(data) {
   
      var newData = new QR8bitByte(data);
      this.dataList.push(newData);
      this.dataCache = null;
    },
    isDark: function(row, col) {
   
      if (row < 0 || this.moduleCount <= row || col < 0 || this.moduleCount <= col) {
   
        throw new Error(row + "," + col);
      }
      return this.modules[row][col];
    },
    getModuleCount: function() {
   
      return this.moduleCount;
    },
    make: function() {
   
      this.makeImpl(false, this.getBestMaskPattern());
    },
    makeImpl: function(test, maskPattern) {
   
      this.moduleCount = this.typeNumber * 4 + 17;
      this.modules = new Array(this.moduleCount);
      for (var row = 0; row < this.moduleCount; row++) {
   
        this.modules[row] = new Array(this.moduleCount);
        for (var col = 0; col < this.moduleCount; col++) {
   
          this.modules[row][col] = null;
        }
      }
      this.setupPositionProbePattern(0, 0);
      this.setupPositionProbePattern(this.moduleCount - 7, 0);
      this.setupPositionProbePattern(0, this.moduleCount - 7);
      this.setupPositionAdjustPattern();
      this.setupTimingPattern();
      this.setupTypeInfo(test, maskPattern);
      if (this.typeNumber >= 7) {
   
        this.setupTypeNumber(test);
      }
      if (this.dataCache == null) {
   
        this.dataCache = QRCodeModel.createData(this.typeNumber, this.errorCorrectLevel, this.dataList);
      }
      this.mapData(this.dataCache, maskPattern);
    },
    setupPositionProbePattern: function(row, col) {
   
      for (var r = -1; r <= 7; r++) {
   
        if (row + r <= -1 || this.moduleCount <= row + r) continue;
        for (var c = -1; c <= 7; c++) {
   
          if (col + c <= -1 || this.moduleCount <= col + c) continue;
          if ((0 <= r && r <= 6 && (c == 0 || c == 6)) || (0 <= c && c <= 6 && (r == 0 || r == 6)) || (2 <= r && r <= 4 && 2 <= c && c <= 4)) {
   
            this.modules[row + r][col + c] = true;
          } else {
   
            this.modules[row + r][col + c] = false;
          }
        }
      }
    },
    getBestMaskPattern: function() {
   
      var minLostPoint = 0;
      var pattern = 0;
      for (var i = 0; i < 8; i++) {
   
        this.makeImpl(true, i);
        var lostPoint = QRUtil.getLostPoint(this);
        if (i == 0 || minLostPoint > lostPoint) {
   
          minLostPoint = lostPoint;
          pattern = i;
        }
      }
      return pattern;
    },
    createMovieClip: function(target_mc, instance_name, depth) {
   
      var qr_mc = target_mc.createEmptyMovieClip(instance_name, depth);
      var cs = 1;
      this.make();
      for (var row = 0; row < this.modules.length; row++) {
   
        var y = row * cs;
        for (var col = 0; col < this.modules[row].length; col++) {
   
          var x = col * cs;
          var dark = this.modules[row][col];
          if (dark) {
   
            qr_mc.beginFill(0, 100);
            qr_mc.moveTo(x, y);
            qr_mc.lineTo(x + cs, y);
            qr_mc.lineTo(x + cs, y + cs);
            qr_mc.lineTo(x, y + cs);
            qr_mc.endFill();
          }
        }
      }
      return qr_mc;
    },
    setupTimingPattern: function() {
   
      for (var r = 8; r < this.moduleCount - 8; r++) {
   
        if (this.modules[r][6] != null) {
   
          continue;
        }
        this.modules[r][6] = (r % 2 == 0);
      }
      for (var c = 8; c < this.moduleCount - 8; c++) {
   
        if (this.modules[6][c] != null) {
   
          continue;
        }
        this.modules[6][c] = (c % 2 == 0);
      }
    },
    setupPositionAdjustPattern: 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值