概述
微信原生开发小程序,使用canvas
组件生成二维码的踩坑记录。canvas原生组件层级过高,会覆盖页面其他元素内容,通过设置z-index
无效,使用cover-view组件
效果也不理想。下面会有两个方法来解决此问题。
用法
1. 使用canvas + weapp-qrcode
插件
通过weapp-qrcode
给canvas组件绘制二维码。因为使用原生组件时,组件在页面中的层级最高,会覆盖其他元素内容,通过修改css样式也会不生效。可通过wx.canvasToTempFilePath
把canvas转成图片链接,通过image组件展示出来解决,转成功后可通过wx:if
去隐藏canvas组件
安装完后记得微信开发者工具构建下npm(顶部状态栏 工具 => 构建npm)
npm install weapp-qrcode --save
注意通过canvas-id
设置id
<canvas wx:if="{{isCanvas}}" canvas-id='qrCode'></canvas>
<image src="{{qrCodeImage}}" style="width:{{qrcode_w}}px; height:{{qrcode_w}}px;" alt=""/>
通过drawQrcode
给canvas
组件绘制二维码,并转成图片链接
import drawQrcode from 'weapp-qrcode'
let that = this
drawQrcode({
width: 200,
height: 200,
canvasId: 'qrCode',
text: 'QRCode_' + this.data.qrCodeInfo.qrlist[0],
callback: (res) => {
// canvas转图片链接
wx.canvasToTempFilePath({
canvasId: 'qrCode',
x: 0,
y: 0,
width: qrcode_w,
height: qrcode_w,
destWidth: qrcode_w,
destHeight: qrcode_w,
success(res) {
that.setData({
qrCodeImage: res.tempFilePath
})
// 转成功后可通过wx:if隐藏canvas组件
wx.nextTick(() => {
that.setData({
isCanvas: false
})
})
},
fail(res) {
console.error(res);
}
})
}
})
2. 使用canvas 2D + weapp-qrcode-canvas-2d
绘制二维码插件
通过获取canvas
节点,再通过weapp-qrcode-canvas-2d
给canvas组件绘制二维码。在开发者工具中显示还是会存在层级覆盖问题,但是真机显示正常,这是正常的,官方也有解释:在工具上,原生组件是用web组件模拟的,因此很多情况并不能很好的还原真机的表现,建议开发者在使用到原生组件时尽量在真机上进行调试
。
安装完后记得微信开发者工具构建下npm(顶部状态栏 工具 => 构建npm)
npm install weapp-qrcode-canvas-2d --save
注意使用canvas 2D
接口时 需设置type
canvas-id
更改为id
<canvas type="2d" id='qrCode2D' style="width:{{qrcode_w}}px; height:{{qrcode_w}}px;"></canvas>
通过drawQrcode2D
直接给canvas
组件绘制二维码
import drawQrcode2D from 'weapp-qrcode-canvas-2d';
wx.nextTick(() => {
wx.createSelectorQuery()
.select("#qrCode2D")
.fields({
node: true,
size: true
})
.exec((res) => {
const canvas = res[0].node
drawQrcode2D({
canvas: canvas,
canvasId: "qrCode2D",
width: qrcode_w,
background: '#ffffff',
foreground: '#000000',
text: 'QRCode_' + this.data.qrCodeInfo.qrlist[0],
callback: (res) => {
console.log(res)
}
})
})
})
结尾
原生小程序开发建议真机测试,下面是官方对原生组件限制的描述。