微信小程序实现生成二维码功能。需要用到canvas组件,设置 type为2d. 需要使用js包weapp-qrcode-canvas-2dhttps://github.com/DoctorWei/weapp-qrcode-canvas-2dweapp-qrcode-canvas-2d 是使用新版canvas-2d接口在微信小程序中生成二维码(外部二维码)的js包。canvas 2d 接口支持同层渲染且性能更佳,可大幅提升生成图片的速度。
使用方法,代码:
1.wxml文件:
<view><button bindtap='createQrcode' type="primary">1.生成二维码</button><canvas id='qrcode' type="2d" style='width:300rpx;height:300rpx;margin-top: 30rpx;margin-left: 100rpx;' ></canvas>
</view>
2.引入js 文件(下载的/weapp.qrcode.esm.js放到utils目录下)
import QRCode from '../../utils/weapp.qrcode.esm.js'
3.生成二维码方法,createQrcode
以下代码中的canvasId就是wxml中canvas定义的id。
// 生成二维码createQrcode() {var that = this;const query = wx.createSelectorQuery()query.select('#qrcode').fields({node: true,size: true}).exec((res) => {var canvas = res[0].node// 调用方法drawQrcode生成二维码QRCode({canvas: canvas,canvasId: 'qrcode',width: that.createRpx2px(300),padding: 10,background: '#ffffff',foreground: '#000000',text: that.data.qrCodeLink,})// 获取临时路径(得到之后,想干嘛就干嘛了)wx.canvasToTempFilePath({canvasId: 'qrcode',canvas: canvas,x: 0,y: 0,width: that.createRpx2px(300),height: that.createRpx2px(300),destWidth: that.createRpx2px(300),destHeight: that.createRpx2px(300),success(res) {// console.log('二维码临时路径:', res.tempFilePath)that.setData({qrcodePath: res.tempFilePath})console.log('二维码临时路径:', that.data.qrcodePath)},fail(res) {console.error(res)}})})
}
单独下载weapp.qrcode.esm.js文件的地址
使用新版canvas-2d接口在微信小程序中生成二维码(外部二维码)的js包-小程序文档类资源-CSDN下载