微信小程序 Canvas 动态生成二维码并保存到本地

let drawQrcode = require("../../../utils/erweima.js");

wxml中:

   <canvas class="code" canvas-id="myQrcode"></canvas>
   <button class='downCode' bindtap='downloadCode'>下载二维码</button>
   <view class="code-content">{{text}}<view class="copy" bindtap="clickCopy">复制</view></view> 

js文件中数据:

data: {
    text: '', // 生成二维码的数据
    imagePath: "" // 保存图片的临时路径
},

通过后台接口拿到数据 text

  // 生成二维码
  draw() {
    drawQrcode({
      width: 200, // 画出的二维码的宽高,单位为px
      height: 200,
      x:20, // 开始画的位置,x轴y轴
      y:20,
      canvasId: 'myQrcode', // 拿到canvas节点
      text: this.data.text // 文本数据
    })
    this.canvasToTempImage() // 画完之后获取临时路径
  },
  
  // 复制文本数据
  clickCopy(e) {
    var that = this;
    wx.setClipboardData({
      data: that.data.text,
      success: function (res) {
        wx.showToast({
          title: '复制成功',
          icon: 'none'
        });
      }
    });
  },
		
  // 获取二维码图片的临时路径
  canvasToTempImage: function () {
    var that = this;
    wx.canvasToTempFilePath({
      canvasId: 'myQrcode',
      success: function (res) {
        var tempFilePath = res.tempFilePath;
        that.setData({
          imagePath: tempFilePath,
        });
      },
      fail: function (res) {
        console.log(res);
      }
    });
  },
 
 // 下载图片
 downloadCode: function (res) {
    var filePath = this.data.imagePath
    console.log('下载中' + filePath)
    wx.saveImageToPhotosAlbum({
      filePath: filePath,
      success: function(res) {
        wx.showToast({
           title: '图片保存成功',
           icon: 'success',
           duration: 2000 //持续的时间
        })
      },
      fail: function (err) {
         console.log(err)
         wx.showToast({
         title: '图片保存失败',
         icon: 'none',
         duration: 2000//持续的时间
         })
      }
    })
  } 
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值