工作中有一个这样的需求,根据APP跳转小程序传进来的地址参数,生成一个公众号的二维码,长按保存到手机的功能
微信本身并不提供将字符转换成二维码的功能,所以使用了第三方插件
插件地址https://github.com/davidshimjs/qrcodejs
使用方法
wxml
<view style="display:flex;flex-direction:column;justify-content:center;">
<canvas class='canvas' style="width:{{qrcodeWidth}}px; height:{{qrcodeWidth}}px;margin:60rpx auto" canvas-id='canvas' bindlongtap='save' ></canvas>
<view style="font-size:16px;text-align:center">1、长按保存图片</view>
<view style="font-size:16px;margin-top:20rpx;text-align:center">2、打开微信扫一扫,选择相册图片</view>
</view>
js文件,下载插件中的qr-code.js,rpx2px.js
const QRCode = require('../../utils/qr-code.js')
import rpx2px from '../../utils/rpx2px.js'
let qrcode;
// 300rpx 在6s上为 150px
const qrcodeWidth = rpx2px(300)
Page({
data: {
imgUrl: '',
qrcodeWidth: qrcodeWidth,
},
onLoad: function (option) {
console.log(decodeURIComponent(option.qrCodeUrl))
this.setData({imgUrl: decodeURIComponent(option.qrCodeUrl)})
qrcode = new QRCode('canvas', {
text: decodeURIComponent(option.qrCodeUrl),// 需要转换的字符串
width: qrcodeWidth,// 二维码宽度
height: qrcodeWidth,// 二维码高度
colorDark: "#000000",// 颜色
colorLight: "white",
correctLevel: QRCode.CorrectLevel.H,
});
},
//保存图片
save: function () {
wx.getSetting({
success: (res) => {
if (res.authSetting['scope.writePhotosAlbum']) {// 判断是否有存储权限
wx.showActionSheet({
itemList: ['保存图片'],
success: function (res) {
if (res.tapIndex == 0) {
qrcode.exportImage(function (path) {
wx.saveImageToPhotosAlbum({
filePath: path,
})
})
}
}
})
}else{
wx.showModal({ // 弹出授权窗口
title: '是否授权保存到相册',
content: '需要获取您的保存图片权限,请确认授权,否则图片将无法保存到相册',
success: function (tip) {
if (tip.confirm) {
wx.openSetting({
success: function (data) {
if (data.authSetting["scope.writePhotosAlbum"] === true) {
wx.showActionSheet({
itemList: ['保存图片'],
success: function (res) {
if (res.tapIndex == 0) {
qrcode.exportImage(function (path) {
wx.saveImageToPhotosAlbum({
filePath: path,
})
})
}
}
})
} else {
wx.showToast({
title: '授权失败',
icon: 'none',
duration: 2000
})
}
}
})
}
}
})
}
},
fail: function(res) {},
complete: () => {}
})
}
})