微信小程序——weapp-qrcode生成二维码插件,并保存到相
2020-07-01 本文已影响0人
遇见sh
1、在wxml中加入canvas用来显示二维码,并在二维码下面加个按钮,保存二维码:
<canvas class="code" canvas-id="myQrcode" style="background:red;width: 200rpx;height:200rpx;"/>
<view class="down" bindtap="saveQrcode">保存到手机相册</view>
2、引入weapp-qrcode:
import QRCode from "../../utils/weapp-qrcode.js" //引入生成二维码的插件
3、在js文件中创建二维码
reateQrcode() {
var that = this;
new QRCode('myQrcode', {
text:'生成二维码要显示的内容',
width: that.createRpx2px(200),
height: that.createRpx2px(200),
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
},
6、生命周期函数--监听页面加载
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
this.reateQrcode()
},