小程序生成酷炫二维码
发布于 2 年前 作者 ping26 1284 次浏览 来自 分享

0.引言

在小程序的业务中会有一些需要展示二维码的场景。静态二维码可以直接存放在本地,使用图片方式展示,但不适合根据用户相关信息生成动态的二维码。本文将介绍根据小程序的canvas能力绘制二维码。

1.方式一:通过wx-qr直接生成

1.0 样例

微信开发者工具打开

1.1 安装

# 通过 npm 安装
npm i wx-qr -S
# 通过 yarn 安装
yarn add wx-qr

1.2 使用组件

首先在你所开发的小程序根目录 app.json 或需要使用该组件的 xxx.json 中引用组件

(注意:请不要将组件命名为 wx-xxx 开头,可能会导致微信小程序解析 tag 失败 )

{
  "usingComponents": {
    "qr-container": "wx-qr"
  }
}

之后就可以在 wxml 中直接使用组件

WXML

<qr-container text="{{qrTxt}}" size="750"></qr-container>

js

Page({
    data: {
        qrTxt: 'https://github.com/liuxdi/wx-qr',
    },
});

当然,还可以支持很多种配置,详见github 或者 码云代码。

2.方式二:基于QRCode.js结合canvas绘制

2.1 引入二维码数据生成库

复制qrcode.js至你的小程序相应目录。

2.2 小程序中建立canvas标签,并给canvas设置长宽

<canvas id="qr" type="2d" style="height: 750rpx;width: 750rpx;"></canvas>

2.3获取canvas实例及上下文

const query = this.createSelectorQuery();
let dpr = wx.getSystemInfoSync().pixelRatio;
query.select('#qr').fields({ nodetruesizetrueidtrue })
  .exec((res) => {
    let { node: canvas, height, width } = res[0];
    let ctx = canvas.getContext('2d');
    canvas.width = width * dpr
    canvas.height = height * dpr
    ctx.scale(dpr, dpr);
  })

2.4 定义一些变量及绘制二维码的数据区

其中__QRCodeModel__是从qrCode.js中导入的

// 二维码的颜色
const colorDark = '#000';
// 获取二维码的大小,因css设置的为750rpx,将其转为px
const rawViewportSize = getPxFromRpx(750);
// 二维码容错率{ L: 1, M: 0, Q: 3, H: 2 }
const correctLevel = 0;
// 创建二维码实例对象,并添加数据进行生成
const qrCode = new QRCodeModel(-1, correctLevel);
qrCode.addData(url);
qrCode.make();

// 每个方向的二维码数量
const nCount = qrCode.moduleCount;
// 计算每个二维码方块的大小
const nSize = getRoundNum(rawViewportSize / nCount, 3)
// 每块二维码点的大小比例
const dataScale = 1;
// 计算出dataScale不为1时,每个点的偏移值
const dataXyOffset = (1 - dataScale) * 0.5;

for (let row = 0; row < nCount; row++) {
  for (let col = 0; col < nCount; col++) {
    // row 和 col 处的模块是否是黑色区
    const bIsDark = qrCode.isDark(row, col);
    // 是否是二维码的图案定位标识区 Position Detection Pattern(如本模块,是三个顶点位置处的大方块)
    const isBlkPosCtr = (col < 8 && (row < 8 || row >= nCount - 8)) || (col >= nCount - 8 && row < 8);
    // 是否是Timing Patterns,也是用于协助定位扫描的
    const isTiming = (row == 6 && col >= 8 && col <= nCount - 8) || (col == 6 && row >= 8 && row <= nCount - 8);
    // 如果是这些区域 则不进行绘制
    let isProtected = isBlkPosCtr || isTiming;
    // 计算每个点的绘制位置(left,top)
    const nLeft = col * nSize + (isProtected ? 0 : dataXyOffset * nSize);
    const nTop = row * nSize + (isProtected ? 0 : dataXyOffset * nSize);
    // 描边色、线宽、填充色配置
    ctx.strokeStyle = colorDark;
    ctx.lineWidth = 0.5;
    ctx.fillStyle = bIsDark ? colorDark : "rgba(255, 255, 255, 0.6)";
    // 如果不是标识区,则进行绘制
    if (!isProtected) {
      ctx.fillRect(
        nLeft,
        nTop,
        (isProtected ? (isBlkPosCtr ? 1 : 1) : dataScale) * nSize,
        (isProtected ? (isBlkPosCtr ? 1 : 1) : dataScale) * nSize
      );
    }
  }
}

此时已经绘制出二维码的数据区:

2.5 绘制图形识别区

// 绘制Position Detection Pattern
ctx.fillStyle = colorDark;
ctx.fillRect(0, 0, 7 * nSize, nSize);
ctx.fillRect((nCount - 7) * nSize, 0, 7 * nSize, nSize);
ctx.fillRect(0, 6 * nSize, 7 * nSize, nSize);
ctx.fillRect((nCount - 7) * nSize, 6 * nSize, 7 * nSize, nSize);
ctx.fillRect(0, (nCount - 7) * nSize, 7 * nSize, nSize);
ctx.fillRect(0, (nCount - 7 + 6) * nSize, 7 * nSize, nSize);
ctx.fillRect(0, 0, nSize, 7 * nSize);
ctx.fillRect(6 * nSize, 0, nSize, 7 * nSize);
ctx.fillRect((nCount - 7) * nSize, 0, nSize, 7 * nSize);
ctx.fillRect((nCount - 7 + 6) * nSize, 0, nSize, 7 * nSize);
ctx.fillRect(0, (nCount - 7) * nSize, nSize, 7 * nSize);
ctx.fillRect(6 * nSize, (nCount - 7) * nSize, nSize, 7 * nSize);
ctx.fillRect(2 * nSize, 2 * nSize, 3 * nSize, 3 * nSize);
ctx.fillRect((nCount - 7 + 2) * nSize, 2 * nSize, 3 * nSize, 3 * nSize);
ctx.fillRect(2 * nSize, (nCount - 7 + 2) * nSize, 3 * nSize, 3 * nSize);
// 绘制Position Detection Pattern 完毕

// 绘制Timing Patterns
const timingScale = 1;
const timingXyOffset = (1 - timingScale) * 0.5;
for (let i = 0; i nCount - 8i += 2) {
  _drawDot(ctx8 + i6nSizetimingXyOffsettimingScale);
  _drawDot(ctx68 + inSizetimingXyOffsettimingScale);
}
// 绘制Timing Patterns 完毕

这时候,一个朴素的二维码就绘制成功啦~

具体代码详见代码片段

该代码只是提供了一个简单二维码的生成逻辑。若需要更复杂的二维码展示功能,还是建议使用wx-qr。欢迎各位提Issue和Star~~

1 回复

哇哦 你好棒棒 学到了学到了

回到顶部