微信小程序——生成二维码

微信小程序专题之生成二维码

小程序生成二维码

注:使用之前需包含__weapp.qrcode.esm.js__ 文件,可到GitHub下载

1. qrcode.wxml

1
<canvas type="2d" style="width: 260px; height: 260px;" id="myQrcode"></canvas>

2. qrcode.js

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// index.js
import drawQrcode from '../../utils/weapp.qrcode.esm.js'

// 获取应用实例
const app = getApp()

// const query = wx.createSelectorQuery()

Page({
  data: {
    qrcodeWidth: 0
  },

  onLoad: function () {
    const query = wx.createSelectorQuery()
    query.select('#myQrcode')
      .fields({
        node: true,
        size: true
      })
      .exec((res) => {
        var canvas = res[0].node

        // 调用方法drawQrcode生成二维码
        drawQrcode({
          canvas: canvas,
          canvasId: 'myQrcode',
          width: 260,
          padding: 30,
          background: '#ffffff',
          foreground: '#000000',
          text: 'hello world',
        })

        // 获取临时路径(得到之后,想干嘛就干嘛了)
        wx.canvasToTempFilePath({
          canvasId: 'myQrcode',
          canvas: canvas,
          x: 0,
          y: 0,
          width: 260,
          height: 260,
          destWidth: 260,
          destHeight: 260,
          success(res) {
            console.log('二维码临时路径:', res.tempFilePath)
          },
          fail(res) {
            console.error(res)
          }
        })
      })
  },
  // 生成二维码
})
comments powered by Disqus
Built with Hugo
Theme Stack designed by Jimmy