Table of Contents
2. Method 2: Drawing based on QRCode.js combined with canvas
Positioning pattern
Functional data
Data Code and Error Correction Code
Home WeChat Applet Mini Program Development How 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
canvas QR code WeChat 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
Copy after login

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"
  }
}
Copy after login

After that, you can use the component directly in wxml

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

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>
Copy after login

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);
  })
Copy after login

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
      );
    }
  }
}
Copy after login

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 完毕
Copy after login

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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Xianyu WeChat mini program officially launched Xianyu WeChat mini program officially launched Feb 10, 2024 pm 10:39 PM

Xianyu's official WeChat mini program has quietly been launched. In the mini program, you can post private messages to communicate with buyers/sellers, view personal information and orders, search for items, etc. If you are curious about what the Xianyu WeChat mini program is called, take a look now. What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3. If you want to use it, you must activate WeChat payment before you can purchase it;

How to create a QR code using wps How to create a QR code using wps Mar 28, 2024 am 09:41 AM

1. Open the software and enter the wps text operation interface. 2. Find the insert option in this interface. 3. Click the Insert option and find the QR code option in its editing tool area. 4. Click the QR code option to pop up the QR code dialog box. 5. Select the text option on the left and enter our information in the text box. 6. On the right side, you can set the shape of the QR code and the color of the QR code.

Implement the drop-down menu effect in WeChat applet Implement the drop-down menu effect in WeChat applet Nov 21, 2023 pm 03:03 PM

To implement the drop-down menu effect in WeChat Mini Programs, specific code examples are required. With the popularity of mobile Internet, WeChat Mini Programs have become an important part of Internet development, and more and more people have begun to pay attention to and use WeChat Mini Programs. The development of WeChat mini programs is simpler and faster than traditional APP development, but it also requires mastering certain development skills. In the development of WeChat mini programs, drop-down menus are a common UI component, achieving a better user experience. This article will introduce in detail how to implement the drop-down menu effect in the WeChat applet and provide practical

Implement image filter effects in WeChat mini programs Implement image filter effects in WeChat mini programs Nov 21, 2023 pm 06:22 PM

Implementing picture filter effects in WeChat mini programs With the popularity of social media applications, people are increasingly fond of applying filter effects to photos to enhance the artistic effect and attractiveness of the photos. Picture filter effects can also be implemented in WeChat mini programs, providing users with more interesting and creative photo editing functions. This article will introduce how to implement image filter effects in WeChat mini programs and provide specific code examples. First, we need to use the canvas component in the WeChat applet to load and edit images. The canvas component can be used on the page

Use WeChat applet to achieve carousel switching effect Use WeChat applet to achieve carousel switching effect Nov 21, 2023 pm 05:59 PM

Use the WeChat applet to achieve the carousel switching effect. The WeChat applet is a lightweight application that is simple and efficient to develop and use. In WeChat mini programs, it is a common requirement to achieve carousel switching effects. This article will introduce how to use the WeChat applet to achieve the carousel switching effect, and give specific code examples. First, add a carousel component to the page file of the WeChat applet. For example, you can use the &lt;swiper&gt; tag to achieve the switching effect of the carousel. In this component, you can pass b

What is the name of Xianyu WeChat applet? What is the name of Xianyu WeChat applet? Feb 27, 2024 pm 01:11 PM

The official WeChat mini program of Xianyu has been quietly launched. It provides users with a convenient platform that allows you to easily publish and trade idle items. In the mini program, you can communicate with buyers or sellers via private messages, view personal information and orders, and search for the items you want. So what exactly is Xianyu called in the WeChat mini program? This tutorial guide will introduce it to you in detail. Users who want to know, please follow this article and continue reading! What is the name of the Xianyu WeChat applet? Answer: Xianyu, idle transactions, second-hand sales, valuations and recycling. 1. In the mini program, you can post idle messages, communicate with buyers/sellers via private messages, view personal information and orders, search for specified items, etc.; 2. On the mini program page, there are homepage, nearby, post idle, messages, and mine. 5 functions; 3.

What should I do if the QR code on Enterprise WeChat cannot be loaded? What should I do if the QR code on Enterprise WeChat cannot be loaded? Mar 14, 2024 pm 10:46 PM

What should I do if the QR code on Enterprise WeChat cannot be loaded? What should we do when we find that the QR code cannot be loaded and cannot be displayed when logging into the computer version of Enterprise WeChat? Here, the editor will give you a detailed introduction to the solution to the problem that the QR code of Enterprise WeChat cannot be loaded. Anyone who needs it Friends, come and take a look! Method 1. Network reasons 1. The network speed may be slow, resulting in slow loading and failure to display. You can disconnect and reconnect. 2. Check the computer's own network problems to see if it is connected to the network. You can restart the network device. Method 2: Maintenance and update: The QR code may not be generated because the version of Enterprise WeChat is too low. You can upgrade the software to the latest version. Method three, firewall 1

Implement the sliding delete function in WeChat mini program Implement the sliding delete function in WeChat mini program Nov 21, 2023 pm 06:22 PM

Implementing the sliding delete function in WeChat mini programs requires specific code examples. With the popularity of WeChat mini programs, developers often encounter problems in implementing some common functions during the development process. Among them, the sliding delete function is a common and commonly used functional requirement. This article will introduce in detail how to implement the sliding delete function in the WeChat applet and give specific code examples. 1. Requirements analysis In the WeChat mini program, the implementation of the sliding deletion function involves the following points: List display: To display a list that can be slid and deleted, each list item needs to include

See all articles