小程序js创建二维码

作者: Stonesy | 来源:发表于2020-12-29 10:45 被阅读0次

    wxqrcode.js 不依赖任何类库,可以生成二维码图片base64编码(data:image/gif;base64,xxx…)

    可以用于小程序页内生成二维码。
    小程序页面wxml代码:
    1.创建canvas节点,以及设置canvas-id。(可以控制该区域不显示,但是必须要存在)

    <canvas style="width: 686rpx;height: 686rpx;background:#f1f1f1;" canvas-id="mycanvas"/>
    

    小程序页面js代码:
    2.引入qrcode.js,将utils/qrcode.js 文件复制到自己工程里,并引入。

    // 注意: 这里xxx是你自己的路径
    let QR = require("xxxx/qrcode.js")  // require方式
    import QR from 'xxxx/qrcode.js'    // es6的方式
    

    3.在js文件中,定义相关的方法,要注意在data中创建imagePath(最终生成的图片路径),可以将img的src属性绑定imagePath

      createQrCode: function (content, canvasId, cavW, cavH) {
        //调用插件中的draw方法,绘制二维码图片
        //this.canvasToTempImage 为绘制完成的回调函数,可根据自己的业务添加
        QR.api.draw(content, canvasId, cavW, cavH, this, this.canvasToTempImage);
      },
      //获取临时缓存图片路径,存入data中
    canvasToTempImage: function (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
            imagePath:tempFilePath,
          });
        },
        fail: function (res) {
          console.log(res);
        }
      });
    },
    

    4.绑定事件,调用createQrCode,生成二维码

    onLoad: function (options) {
        var that = this;
        this.createQrCode('wxapp-qrcode', 'mycanvas', 300, 300)
      },
    

    1.基于canvas绘图制作二维码:https://github.com/demi520/wxapp-qrcode

    2.基于img,base64输出二维码:https://git.oschina.net/cxing/wxqrcode.git

    3.提供了不同语言的生成二维码: https://github.com/kazuhikoarase/qrcode-generator

    4.二维码官网: http://www.qrcode.com/zh/

    5.phpqrcode官网:http://phpqrcode.sourceforge.net/

    相关文章

      网友评论

        本文标题:小程序js创建二维码

        本文链接:https://www.haomeiwen.com/subject/rilfoktx.html