在前端项目里,如何创建和运用二维码
在开发一个取件的小程序与 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码。 根据操作环境,有四个级别可供选择。
Level | Error resistance |
---|---|
L (Low) | ~7% |
M (Medium) | ~15% |
Q (Quartile) | ~25% |
H (High) | ~30% |
级别越高,提供的抗错误性越好,但会降低符号的容量
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:指定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 前端路由原理与实现
推荐阅读
-
在前端项目里,如何创建和运用二维码
-
在Vue项目里如何实现扫描二维码的功能
-
前端搭建指南:调试本地开发环境的实用技巧 - 在CLI脚手架项目里,别忘了添加库文件及其版本依赖 1. 实时联动与修改: a) 首先确保在当前CLI脚手架项目的`package.json`依赖中加入所用库文件及其正确版本。 b) 通过npm link在本地创建硬连接,使得库与项目能实时修改、同步。运行如下命令: ``` $ cd your-lib-dir $ npm link $ cd your-cli-dir $ npm link your-lib ``` 2. 模拟部署环境: 当需测试线上环境时,解除本地软链接。回到库文件目录并执行: ``` $ cd your-lib-dir $ npm unlink ``` 同样,在CLI项目目录执行: ``` $ cd your-cli-dir $ npm uninstall your-lib --save ``` 注意此时可能会出现因缺少库文件依赖导致的错误,但可暂且忽略,这样能避免将来遗漏或重复安装的问题。 3. 发布后的操作: 如果库已上线,可先清空CLI项目的`node_modules`目录(`rm -rf node_modules`),然后重新安装所有依赖: ``` $ npm install ``` 通过以上步骤,您就能顺畅地调试和部署您的脚手架项目了。 总结 `link` & `unlink` 命令的运用: 1. `npm link`:在本地创建硬连接,便于实时协作与同步。 2. `npm unlink`:模拟线上环境并解除软链接,为正式部署做准备。