二维码在生活中无处不在,之前我也使用过java的zxing库生成过二维码,功能很强大。
但是其实nodejs上也有很多第三方库能够生成二维码。今天我们就是使用qrcode这个库来生成二维码。
效果展示
在线示例: http://www.lolmbbs.com/qr

详细代码
生成二维码:
const qrCode = require('qrcode')
class QrController {
async create (ctx) {
const { text = 'Luban', options } = ctx.request.body
const qrOptions = {
type: 'image/png',
width: 180,
margin: 0,
scale: 1,
color: {
dark: '#000000',
light: '#ffffff'
},
errorCorrectionLevel: 'M',
quality: 1
}
Object.assign(qrOptions, options)
const imgData = await qrCode.toDataURL(text, qrOptions)
return ctx.success({ imgData })
}
}
module.exports = new QrController()
下载二维码:
const a = document.createElement('a')
const event = new MouseEvent('click')
a.download = '二维码'
a.href = this.imgSrc
a.dispatchEvent(event)
主要参数解释
-
type: 生成图片类型 主要包括 image/png 、image/jpeg 、 image/web 这三种类型. ps: 但是我在代码中即使设置type为image/jpeg ,发现生成的图片还是png,后来仔细阅读文档才知道toDataURL这个方法只支持生成png类型的图片…  -
width: 二维码的宽度 发现没有height字段设置,可能是生成的二维码都是正方形吧 -
margin: 内边距 内边距设置为10  内边距设置为0  -
scale 放缩的倍数 如果设置了width,优先生效width,则此参数无用. 放缩比例为5  放缩比例为10  -
color.light: 前景色 -
color.night: 背景色 默认的前景色是黑色,背景色为白色。 -
errorCorrectionLevel 纠错级别  二维码即使有部分显示不了,依然可以识别出二维码的内容,这就是二维码的纠错。 L级别的纠错代表只要残缺度小于7%,就可以被识别出,以此类推
|