微信小程序·canvas生成二维码图
注意:微信开发者工具显示不兼容,需要真机看效果


html】
<canvas type="2d" style="width: 260px; height: 260px;" id="myQrcode"></canvas>
js】
// 将 全部js文件导入拷贝到项目路所需的目录下, // 将 weapp.qrcode.esm.js 导入到js页面中 import drawQrcode from '../../utils/weapp.qrcode.esm.js'
getQrcode() { //生成二维码
const query = wx.createSelectorQuery()
query.select('#myQrcode')
.fields({
node: true,
size: true
})
.exec(async (res) => {
var canvas = res[0].node
var thiss = this;
var img = canvas.createImage();
img.src = "../../logo.jpg" //logo图片地址
img.onload = function () {
// img.onload完成后才能调用 drawQrcode方法
var options = {
canvas: canvas,
canvasId: 'myQrcode',
width: 260,
padding: 30,
paddingColor: '#fff',
background: '#fff',
foreground: '#000000',
text: '123456789', //二维码内容
image: {
imageResource: img,
width: 50, // 建议不要设置过大,以免影响扫码
height: 50, // 建议不要设置过大,以免影响扫码
round: true // Logo图片是否为圆形
}
}
drawQrcode(options)
// 获取临时路径
wx.canvasToTempFilePath({
x: 0,
y: 0,
width: 260,
height: 260,
destWidth: 600,
destHeight: 600,
canvasId: 'myQrcode',
canvas: canvas,
success(res) {
console.log('二维码临时路径为:', res.tempFilePath)
},
fail(res) {
console.error(res)
}
})
};
})
},options
Type: Object
| 参数 | 必须 | 说明 | 示例 |
|---|---|---|---|
| canvas | 必须 | 画布标识,传入 canvas 组件实例 | |
| canvasId | 非 | 绘制的canvasId | 'myQrcode' |
| text | 必须 | 二维码内容 | ‘123456789’ |
| width | 非 | 二维码宽度,与canvas的width保持一致 | 260 |
| padding | 非 | 空白内边距 | 20 |
| paddingColor | 非 | 内边距颜色 | 默认与background一致 |
| background | 非 | 二维码背景颜色,默认值白色 | '#ffffff' |
| foreground | 非 | 二维码前景色,默认值黑色 | '#000000' |
| typeNumber | 非 | 二维码的计算模式,默认值-1 | 8 |
| correctLevel | 非 | 二维码纠错级别,默认值为高级,取值:{ L: 1, M: 0, Q: 3, H: 2 } | 1 |
| image | 非 | 在 canvas 上绘制图片,层级高于二维码,v1.1.1+版本支持。 | {imageResource: '', width:80, height: 80, round: true} |