前端开发中二维码的生成与使用

7,589 阅读5分钟

在开发一个取件的小程序与 nodejs 服务端的过程中发现,如果使用网上现有的二维码生成 API ,存在某些问题比如请求需要较长时间,数据格式较为固定,由于整体业务上也不需要二维码的风格化,最好可以前端与 nodejs 服务端通用。

经过简单的调研选择了 QRCode.js

QRCode.js 项目

QRCode.js 是一个用于生成二维码的 JavaScript 库。主要是通过获取 DOM 的标签,再通过 HTML5 Canvas 绘制而成,不依赖任何库。他支持 nodejs 端,浏览器端,以及小程序端。

1. 安装 QRCode.js

npm install --save qrcode

2. 配置生成二维码的属性

const QRCode = require('qrcode')
const options = {
    errorCorrectionLevel: 'H',
    type: 'terminal',
    quality: 0.95,
    margin: 1,
    color: {
        dark: '#000',
        light: '#FFF',
    },
}
  • errorCorrectionLevel:纠错功能使您即使符号变脏或损坏也能成功扫描QR码。 根据操作环境,有四个级别可供选择。
LevelError resistance
L (Low)~7%
M (Medium)~15%
Q (Quartile)~25%
H (High)~30%

级别越高,提供的抗错误性越好,但会降低符号的容量

ModeLMQH
Numeric7089559639933057
Alphanumeric4296339124201852
Byte2953233116631273
Kanji181714351024784
  • color:指定QR码图像的颜色

dark:二维码主体颜色,light:二维码背景颜色

  • Type:指定期望的输出类型,例如数据URL中的 image / png,image / jpeg,image / webp和utf8,SVG,字符串中的终端。

  • quality:设置图像的质量,范围为0-1。 默认值为0.92,仅适用于image / jpeg和image / webp类型

  • width:设置图像的边长 如果width太小而不能包含二维码的全部信息符号,则此选项将被忽略。

  • margin:设置图像的外边框距离

  • scale:设置每几个像素为一个信息点默认为 4

3. 设置输出

浏览器端的使用方法

可以通过渲染到 Canvas 画布进行使用

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

使用前需要使用打包工具构建依赖

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

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

或者直接渲染 base64 或者 图像文件 (png ,svg ,jpeg)

nodejs-server 端常见使用方法

转成终端可输出的字符串

toString(text, [options], [cb(error, string)]) 返回QR码的字符串表示形式。 如果选择的输出格式是svg,它将返回一个包含xml代码的字符串。


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

转成包含二维码图片信息的 Base64 编码 url toDataURL(text, [options], [cb(error, url)]) 返回包含QR码图像表示形式的数据URI。 目前仅适用于 image / png类型。

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

转成图片形式存储 toFile(path, text, [options], [cb(error)])

将QR Code保存到图像文件。 如果未指定options.type,则将从文件扩展名中猜测格式。

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

完整 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)
    })

QRcode 同时支持 ES5 / ES6 / ES7 的语法

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)
  }
}

在微信小程序中使用

yingye 老师提供的方案 weapp.qrcode.js

weapp.qrcode.js

先在 wxml 文件中,创建绘制的 canvas,并定义好 width, height, canvasId 。

直接引入 js 文件,使用 drawQrcode() 绘制二维码。

由于目前微信小程序已全面支持 npm ,可以选择直接安装,记得要构建 npm 包

npm install weapp-qrcode --save

基本使用

import drawQrcode from 'weapp-qrcode'

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

快速生成条码和二维码的方案

wxbarcode

安装

$ npm install wxbarcode

使用方法

import wxbarcode from 'wxbarcode'

wxbarcode.barcode('barcode', '1234567890123456789', 680, 200);
wxbarcode.qrcode('qrcode', '1234567890123456789', 420, 420);

条形码

函数名:barcode

函数原型:barcode(id, code, width, height)

参数:

  • id: wxml文件中的 Canvas ID
  • code: 用于生成条形码的字符串
  • width: 生成的条形码宽度,单位 rpx
  • height: 生成的条形码高度,单位 rpx

二维码

函数名:qrcode

函数原型:qrcode(id, code, width, height)

参数:

  • id: wxml文件中的 Canvas ID
  • code: 用于生成二维码的字符串
  • width: 生成的二维码宽度,单位 rpx
  • height: 生成的二维码高度,单位 rpx

总结

调研了很多解决方案,node-qrcode 解决了我大部分问题。小程序社区也有很多的方案,也可以在跨端框架中使用,由于不是生产级项目也没有去调研尝试。但基本应该足以满足需求。

❤️ 感谢大家

如果你觉得这篇内容对你挺有有帮助的话:

点赞支持下吧,让更多的人也能看到这篇内容(收藏不点赞,都是耍流氓 -_-)

关注公众号咸鱼爱前端,我们一起学习一起进步。

觉得不错的话,也可以阅读其他文章(感谢朋友的鼓励与支持🌹🌹🌹):

三个网站玩转 Grid 布局

Nodejs 实现定时爬虫

React-Query 让你的状态管理更优雅

前端页面布局学习神器

面试必备知识点之深浅拷贝

SPA 前端路由原理与实现