思路
使用weapp-qrcode在微信小程序里生成二维码,但是这个库只能给你生成到画布上,但是我查看微信小程序官方文档发现画布并没有图片的类似于show-menu-by-longpress这样的属性,所以我们只能通过其他途径把他转成图片。
微信小程序官方文档有canvasToTempFilePath这个 API可以把画布临时转成图片地址,我们把它显示在页面,然后把画布隐藏起来,这样一来就实现了我们想要的结果。
一、安装weapp-qrcode
npm i weapp-qrcode
二、实现步骤
1.使用weapp-qrcode在画布上生成二维码
<button bindtap="showQRCode">生成二维码<button>
<canvas style="width: 200px; height: 200px;" canvas-id="myQrcode" id="myQrcode"></canvas>
import drawQrcode from 'weapp-qrcode'
Page({
data: {
showModal: false
},
showQRCode() {
this.setData({
showModal: true
})
drawQrcode({
width: 200,
height: 200,
canvasId: 'myQrcode',
text: '不秃的Summer'
})
},
hideModal() {
// 关闭弹窗
this.setData({
showModal: false
});
},
2.把画布上的二维码转换成图片地址显示到页面上
注意:如果想让image组件长按弹起保存和转发的原生弹窗,要加how-menu-by-longpress,默认值是false
<button bindtap="showQRCode">生成二维码<button>
<view show="{{ showModal }}">
<view class="qr-modal-content" style="background: #000;">
<image style="width: 200px; height: 200px;" class="qrcode" show-menu-by-longpress="true" src="{{qrcodeUrl}}" mode="aspectFit"></image>
</view>
</view>
<canvas style="width: 200px; height: 200px; position: absolute; top: -999px;" canvas-id="myQrcode" id="myQrcode"></canvas>
这里我先要找到页面上这个画布,然后将画布通过微信自带的API转换成图片
import drawQrcode from 'weapp-qrcode'
Page({
data: {
qrcodeUrl: '',
showModal: false
},
showQRCode() {
let that = this;
that.setData({
showModal: true
})
drawQrcode({
width: 200,
height: 200,
canvasId: 'myQrcode',
text: '不秃的Summer'
})
// 创建一个选择器查询对象
const query = wx.createSelectorQuery();
// 执行查询并获取 canvas 节点的实例
query.select('#myQrcode').boundingClientRect()
// 查询结束后执行回调函数
query.exec((res) => {
if (res[0]) {
// res[0] 是 canvas 节点信息,确保节点存在
wx.canvasToTempFilePath({
canvasId: 'myQrcode',
success(res) {
const tempFilePath = res.tempFilePath;
console.log(tempFilePath);
that.setData({
qrcodeUrl: tempFilePath
})
},
fail(err) {
console.error( err);
}
});
} else {
console.error('未能找到对应的 canvas 节点');
}
});
},
hideModal() {
// 关闭弹窗
this.setData({
showModal: false
});
},