search
HomeWeChat AppletMini Program DevelopmentHow to use the mini program's canvas to draw QR codes?

How to use the mini program's canvas to draw QR codes?

Jan 06, 2022 am 10:11 AM
canvasQR codeWeChat applet

How to generate QR code in WeChat applet? The following article will introduce to you how to draw QR codes using the canvas capability of the mini program. I hope it will be helpful to you!

How to use the mini program's canvas to draw QR codes?

#In the WeChat mini program business, there will be some scenarios where QR codes need to be displayed. Static QR codes can be stored directly locally and displayed using pictures, but they are not suitable for generating dynamic QR codes based on user-related information. This article will introduce how to draw QR codes using the canvas capability of the mini program.

1 Method 1: Generate directly through wx-qr

1.1 DEMO

WeChat developer tools open to view

How to use the mini programs canvas to draw QR codes?
Including background image
How to use the mini programs canvas to draw QR codes?
Included logo
How to use the mini programs canvas to draw QR codes?
Contains logo background image

1.2 Install

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

# 通过 yarn 安装
yarn add wx-qr

1.3 Use the component

First develop it in your The component is referenced in the root directory of the mini program app.json or

xxx.json

where the component needs to be used (note: please do not name the component wx-xxx may cause the WeChat applet to fail to parse the tag)

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

After that, you can use the component directly in wxml

<qr-container text="{{qrTxt}}" size="750"></qr-container>
Page({
    data: {
        qrTxt: &#39;https://github.com/liuxdi/wx-qr&#39;,
    },
});

Of course, there are also It can support many configurations, please see the github or codecloud documentation for details.

2. Method 2: Drawing based on QRCode.js combined with canvas

2.0 Components of QR code

How to use the mini programs canvas to draw QR codes?

Positioning pattern
  • Position Detection Pattern is a positioning pattern used to mark the rectangular size of the QR code. These three positioning patterns have white edges and are called Separators for Postion Detection Patterns. The reason why there are three instead of four means that three can mark a rectangle.

  • Timing Patterns are also used for positioning. The reason is that there are 40 sizes of QR codes. If the size is too large, there needs to be a standard line, otherwise it may be scanned crookedly.

  • Alignment Patterns Only QR codes of Version 2 and above (including Version 2) require this stuff, which is also used for positioning.

Functional data
  • Format Information exists in all sizes and is used to store some formatted data.

  • Version Information >= Version 7 or above, two 3 x 6 areas need to be reserved to store some version information.

Data Code and Error Correction Code
  • Except for the above places, the remaining places store Data Code and Error Correction Code.

2.1 Introducing the QR code data generation library

Copyqrcode.js to you The corresponding directory of the mini program.

2.2 Create a canvas tag in the mini program and set the length and width of the canvas

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

2.3 Get the canvas instance and Context

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

2.4 Define some variables and draw the data code area of ​​the QR code

QRCodeModel is imported from qrCode.js

// 二维码的颜色
const colorDark = &#39;#000&#39;;
// 获取二维码的大小,因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
      );
    }
  }
}

At this time, the data code area of ​​the QR code has been drawn:

How to use the mini programs canvas to draw QR codes?

2.5 Draw the graphic recognition area

// 绘制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 - 8; i += 2) {
  _drawDot(ctx, 8 + i, 6, nSize, timingXyOffset, timingScale);
  _drawDot(ctx, 6, 8 + i, nSize, timingXyOffset, timingScale);
}
// 绘制Timing Patterns 完毕

At this time, a simple QR code is drawn successfully~

How to use the mini programs canvas to draw QR codes?

For details, please refer to the WeChat applet code snippet

https://developers.weixin.qq.com/s/WHJj73mX7bwv

This code only provides a simple two-dimensional Code generation logic. If you need a more complex QR code display function, it is recommended to use wx-qr or refer to the specific code inside. Welcome to submit Issues and Stars~~

[Related learning recommendations: 小program development tutorial]

The above is the detailed content of How to use the mini program's canvas to draw QR codes?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use