微信小程序业务-字符串生成二维码(weapp-qrcode)
前言
邂逅weapp-qrcode
基本使用
.wxml
<canvas class="icon-qrcode" style="width: 180px; height: 180px" canvas-id="myQrcode" />
.js
import drawQrcode from "../../../../utils/weapp-qrcode"; drawQrcode({ width: 180, height: 180, canvasId: myQrcode, text: 转换为二维码的字符串, })
详细参数
小程序组件中使用
如果是在小程序组件中使用,必须得传_this参数,否则会导致生成空白canvas
drawQrcode({ width: 180, height: 180, canvasId: myQrcode, text: 转换为二维码的字符串, _this: this, })
注意传入的this指向一定要指向组件对象
image属性详解
image属性的作用是在二维码中间生成一张小图,如下图所示
drawQrcode({ width: 180, height: 180, canvasId: myQrcode, text: 转换为二维码的字符串, _this: this, image: { imageResource: /images/userIcon.png, dx: 60, dy: 60, dWidth: 60, dHeight: 60, } })
-
imageResource表示图片路径,仅支持小程序本地路径,网络图片即使配置域名也无法生效 dx:x轴便宜量,dy:y轴便宜量,dWidth/dHeight:图片宽高, 其中的图片居中位置需要自己计算,通过(dx = (canvas大小 - dWidth)/ 2)得到x轴偏移量,y轴同理
想使用网络图片?
为什么不能直接使用网络图片? 实际上weapp-qrcode的image属性是通过CanvasContext.drawImage实现的,相信细心的你可以在参数说明中发现。 而CanvasContext.drawImage是不支持直接使用网络图片
如何使用网络图片? 根据文档中的提示,解决办法已经很明显了,我们可以先调用getImageInfo或者downloadFile,在成功的回调里面使用weapp-qrcode
wx.downloadFile({ url: 网络图片路径, success: (res) => { console.log(res) drawQrcode({ width: 180, height: 180, canvasId: myQrcode, text: 转换为二维码的字符串, _this: this, image: { imageResource: res.tempFilePath, dx: 60, dy: 60, dWidth: 60, dHeight: 60, } }) } })
-
这样使用的缺点也很明显,延迟了二维码的生成时间
参考地址
上一篇:
uniapp开发微信小程序-2.页面制作
下一篇:
微信小程序-云函数连接MySQL数据库