参考:https://segmentfault.com/a/1190000012675069
源码地址:https://github.com/tomfriwel/weapp-qrcode
最近的微信小程序项目中有这样一个需求,点击按钮生成保存店铺信息(小程序为交易平台系统)的二维码,可扫码进入店铺。各种百度之后发现此种方法方便易用,以此学习并记录下来,用的是原文作者改版后的生成二维码工具weapp-qrcode.js,demo里有很多文件,只需将util下的weapp-qrcode.js拷贝到项目中即可
页面wxml中放置绘制二维码的canvas:
<canvas class='canvas' canvas-id='canvas' bindlongtap='save'>canvas>
js页面需引入weapp-qrcode.js文件
var QRCode = require('../../utils/weapp-qrcode.js')
onload中
onLoad: function (options) {
qrcode = new QRCode('canvas', {
// usingIn: this,
text: "code=123456",
width: 150,
height: 150,
colorDark: "#1CA4FC",
colorLight: "white",
correctLevel: QRCode.CorrectLevel.H,
});
}
usingIn 为可选参数,详情清查卡在自定义组件使用时失效及解决思路 #1
text 为需要转化为二维码的字符串;
width 和 height 为绘制出的二维码长宽,这里设置为跟canvas同样的长宽;
colorDark 和 colorLight 为二维码交替的两种颜色;
correctLevel 没有细看源码,命名上看应该是准确度;
如果需要再次生成二维码,调用qrcode.makeCode(‘text you want convert’)
wxml:
<view class='input-wrapper'>
<input bindinput='inputHandler' bindconfirm='confirmHandler' placeholder='输入需要转换为二维码的字符串' value='{{text}}'>input>
view>
<view class='button-wrapper'>
<button bindtap='tapHandler'>转为二维码button>
view>
<canvas class='canvas' canvas-id='canvas' bindlongtap='save'>canvas>
js:
var QRCode = require('../../utils/weapp-qrcode.js')
var qrcode;
Page({
data: {
text: '',
image: ''
},
onLoad: function (options) {
qrcode = new QRCode('canvas', {
// usingIn: this,
text: "",
image:'/images/bg.jpg',
width: 150,
height: 150,
colorDark: "#1CA4FC",
colorLight: "white",
correctLevel: QRCode.CorrectLevel.H,
});
},
confirmHandler: function (e) {
var value = e.detail.value
qrcode.makeCode(value)
},
inputHandler: function (e) {
var value = e.detail.value
this.setData({
text: value
})
},
tapHandler: function () {
// 传入字符串生成qrcode
qrcode.makeCode(this.data.text)
},
save: function () {
console.log('save')
wx.showActionSheet({
itemList: ['保存图片'],
success: function (res) {
console.log(res.tapIndex)
if (res.tapIndex == 0) {
qrcode.exportImage(function (path) {
wx.saveImageToPhotosAlbum({
filePath: path,
})
})
}
}
})
}
})
wxss:
.input-wrapper {
margin: 40rpx auto 0 auto;
width: 600rpx;
height: 88rpx;
border: 2rpx solid #ddd;
border-radius: 16rpx;
padding-left: 10rpx;
padding-right: 10rpx;
}
.input-wrapper input {
font-size: 32rpx;
line-height: 88rpx;
height: 100%;
}
.button-wrapper {
margin-top: 40rpx;
}
.canvas {
margin: 220rpx auto;
width: 150px;
height: 150px;
}