1、在wxml中加入canvas用来显示二维码,并在二维码下面加个按钮,保存二维码:
<canvas class="code" canvas-id="myQrcode" style="background:#fff;width: 640rpx;height: 640rpx;"/> <view class="down" bindtap="saveQrcode">保存到手机相册</view>2、引入weapp-qrcode:
import QRCode from '../../../utils/weapp-qrcode.js';3、创建二维码
createQrcode() {
var that = this;
var codeJson = {
id: that.data.id,
type: 2, //1 用户 2商家 3群组 4优惠券
}
new QRCode('myQrcode', {
text: JSON.stringify(codeJson),
width: that.createRpx2px(640),
height: that.createRpx2px(640),
padding: 12, // 生成二维码四周自动留边宽度,不传入默认为0
correctLevel: QRCode.CorrectLevel.L, // 二维码可辨识度
callback: (res) => {
// 接下来就可以直接调用微信小程序的api保存到本地或者将这张二维码直接画在海报上面去,看各自需求
that.data.qrcodePath = res.path;
}
})
},
4、保存到本地
// 用户二维码保存到本地相册
saveQrcode: function () {
var that = this;
wx.getImageInfo({
src: that.data.qrcodePath,
success: function (ret) {
var path = ret.path;
wx.saveImageToPhotosAlbum({
filePath: path,
success(result) {
if (result.errMsg === 'saveImageToPhotosAlbum:ok') {
wx.showToast({
title: '保存成功',
})
}
}
})
}
})
},
5、将rpx转px。由于二维码的canvas在页面中,显示,为了适应屏幕,采用了rpx作为单位。但是创建二维码new QRCode时,传入的是px,所以,为了传入的尺寸和canvas一样大,需要使用createRpx2px方法,将rpx转为px:
createRpx2px(rpx) {
return wx.getSystemInfoSync().windowWidth / 750 * rpx
},
下载weapp-qrcode.js