需求:
动态获取分享码地址,生成一个二维码,可以保存二维码图片,然后分享给其他人。
解决方法:
由于小程序中无法对dom操作,所以考虑使用canvas画出二维码,可借助第三方库weapp-qrcod.js
下面介绍具体使用方法:
- 下载weapp-qrcode.js,且引入页面中,下载地址https://github.com/tomfriwel/weapp-qrcode/blob/master/dist/weapp-qrcode.js
const QRCode= require('../../utils/qrcode.js')
2.wxml中引入canvas, js中对canvas初始化
<canvas class='canvas' canvas-id='canvas' style="width: 100%;height: 100%" bindlongtap="save" ></canvas>
wx.request({
url: '...',
method:'POST',
data:{},
success: function(res) {
if(res.data.data) {
if(qrcode) {
that.setData({
qrcode:that.data.qrcode.makeCode(res.data.data),
showLoading: false
})
}else{
that.setData({
qrcode:new QRCode('canvas', {
text: res.data.data,
width: 220,
height: 220,
colorDark: "#000000",
colorLight: "#ffffff",
correctLevel: QRCode.CorrectLevel.H,
})
})
that.setData({
showLoading:false
})
}
}
}
})
3.实现长按保存
save: function() {
let that = this;
wx.showActionSheet({
itemList: ['保存图片'],
success: function(res) {
if (res.tapIndex == 0) {
that.data.qrcode.exportImage(function(path) {
wx.saveImageToPhotosAlbum({
filePath: path,
success: function() {
wx.showToast({
title:'保存成功'
})
}
})
})
}
}
})
},