In the process of developing a fetching small program and nodeJS server, it is found that if the existing TWO-DIMENSIONAL code generation API on the Internet is used, there are some problems, such as the request takes a long time, the data format is relatively fixed, because the overall business does not need the stylization of two-dimensional code, it is better to be common with the front-end and nodeJS server.

After a simple investigation, Qrcode.js was selected

QRCode. Js project

Qrcode.js is a JavaScript library for generating qr codes. It is mainly made by obtaining the DOM tag and drawing it through HTML5 Canvas, without relying on any library. It supports nodeJS side, browser side, and small program side.

1. Install the QRCode. Js

npm install --save qrcode
Copy the code

2. Configure the properties for generating qr codes

const QRCode = require('qrcode')
const options = {
    errorCorrectionLevel: 'H'.type: 'terminal'.quality: 0.95.margin: 1.color: {
        dark: '# 000'.light: '#FFF',}}Copy the code
  • ErrorCorrectionLevel: The errorCorrectionLevel enables you to scan QR codes successfully even if the symbols are dirty or damaged.

There are four levels to choose from, depending on the operating environment.

Level Error resistance
L (Low) ~ 7%
M (Medium) ~ 15%
Q (Quartile) ~ 25%
H (High) ~ 30%

The higher the level, the better error resistance it provides, but reduces the capacity of the symbol

Mode L M Q H
Numeric 7089 5596 3993 3057
Alphanumeric 4296 3391 2420 1852
Byte 2953 2331 1663 1273
Kanji 1817 1435 1024 784
  • Color: Specifies the color of the QR code image

Dark: main color of QR code, light: background color of QR code

  • Type: Specifies the desired output Type, such as image/PNG, image/JPEG, image/webp and UTF8 in the data URL, SVG, terminal in the string.

  • Quality: Sets the image quality in a range of 0-1. The default value is 0.92 and only applies to image/JPEG and Image/webp types

  • Width: Sets the length of the image side

If width is too small to contain all the information symbols of the QR code, this option is ignored.

  • Margin: Sets the outer border distance of the image

  • Scale: Set every few pixels to an information point. The default is 4

3. Set the output

How to use the browser

It can be used by rendering to Canvas

<html>
  <body>
    <canvas id="canvas"></canvas>
    <script src="bundle.js"></script>
  </body>
</html>
Copy the code

Use a packaging tool to build dependencies before use

var QRCode = require('qrcode')
var canvas = document.getElementById('canvas')

QRCode.toCanvas(canvas, 'sample text'.function (error) {
  if (error) console.error(error)
  console.log('success! ');
})
Copy the code

Or directly render base64 or image files (PNG, SVG, JPEG)

Nodejs-common usage on the server

Convert to a string that can be output by the terminal

ToString (text, [options], [cb(error, string)]) Returns a string representation of the QR code. If the selected output format is SVG, it returns a string containing the XML code.


QRCode.toString([
    { data: 'qrcode test in nodejs'.mode: 'byte' },
]
).then(qrImage= > {
    console.log("terminal", qrImage)
}).catch(err= > {
    console.error(err)
})
Copy the code

ToDataURL (text, [options], [CB (error, URL)])) returns the data URI containing the image representation of the QR code. Currently only available for image/PNG types.

QRCode.toDataURL('qrcode test in nodejs', options).then(qrImage= > {
    console.log("URL", qrImage)
}).catch(err= > {
    console.error(err)
})
Copy the code

ToFile (path, text, [options], [cb(error)])

Save the QR Code to the image file. If options.type is not specified, the format is guessed from the file extension.

QRCode.toFile('./images/qrCode.png'."qrcode test in nodejs", options)
    .then(() = > {
        console.log("success")
    }).catch(err= > {
        console.error(err)
    })

Copy the code

Complete Node-server demo

const QRCode = require('qrcode')

const options = {
    errorCorrectionLevel: 'H'.type: 'terminal'.quality: 0.95.margin: 1.color: {
        dark: '# 000'.light: '#FFF',
    },
}

QRCode.toString([
    { data: 'qrcode test in nodejs'.mode: 'byte' },
]
).then(qrImage= > {
    console.log("terminal", qrImage)
}).catch(err= > {
    console.error(err)
})

QRCode.toDataURL('qrcode test in nodejs', options).then(qrImage= > {
    console.log("URL", qrImage)
}).catch(err= > {
    console.error(err)
})

QRCode.toFile('./images/qrCode.svg'."qrcode test in nodejs", options)
    .then(() = > {
        console.log("success")
    }).catch(err= > {
        console.error(err)
    })

Copy the code

QRcode also supports ES5 / ES6 / ES7 syntax

import QRCode from 'qrcode'

// With Callback
QRCode.toString('http://www.google.com'.function (err, string) {
  if (err) throw err
  console.log(string)
})
// With promises
QRCode.toDataURL('I am a pony! ')
  .then(url= > {
    console.log(url)
  })
  .catch(err= > {
    console.error(err)
  })

// With async/await
const generateQR = async text => {
  try {
    console.log(await QRCode.toDataURL(text))
  } catch (err) {
    console.error(err)
  }
}
Copy the code

It is used in wechat applet

Teacher Yingye provided program app.qrcode.js

weapp.qrcode.js

First in the WXML file, create the canvas, and define the width, height, canvasId.

Import the JS file directly and draw the QR code using drawQrcode().

Because the current micro channel small program has fully support NPM, you can choose to install directly, remember to build NPM package

npm install weapp-qrcode --save

Copy the code

The basic use

import drawQrcode from 'weapp-qrcode'

drawQrcode({
  width: 200.height: 200.canvasId: 'myQrcode'.text: 'https://github.com/yingye'
})
Copy the code

Quick generation of bar code and TWO-DIMENSIONAL code scheme

wxbarcode

The installation

$ npm install wxbarcode
Copy the code

Method of use

import wxbarcode from 'wxbarcode'

wxbarcode.barcode('barcode'.'1234567890123456789'.680.200);
wxbarcode.qrcode('qrcode'.'1234567890123456789'.420.420);
Copy the code

Bar code

Function name: barcode

Function prototype: barcode(id, code, width, height)

Parameters:

  • Id: Canvas ID in the WXML file
  • Code: The string used to generate the barcode
  • Width: generated barcode width, in RPX
  • Height: the height of the generated bar code, in RPX

Qr code

Function name: qrcode

Function prototype: qrcode(id, code, width, height)

Parameters:

  • Id: Canvas ID in the WXML file
  • Code: The string used to generate a QR code
  • Width: width of the generated QR code (unit: RPX)
  • Height: Height of the generated QR code, unit RPX

conclusion

Researching a lot of solutions, Node-qrCode solved most of my problems. The mini program community also has a number of solutions, which can also be used in the cross-end framework, because it is not a production level project and has not been investigated to try. But basically it should be enough to meet demand.

❤️ Thank you all

If you found this helpful:

Like support, let more people can also see this content.

Pay attention to the public number xianyu love front end, we learn together and progress together.

If you feel good, you can also read other articles (thanks to friends for their encouragement and support 🌹🌹🌹) :

Three websites play with Grid layout

Nodejs implements periodic crawlers

React-query makes your state management more elegant

Front-end page layout learning artifact

A deep copy of the interview essentials

Principle and implementation of SPA front-end routing