js生成二维码
//在项目文件夹中执行:
npm install --save qrcode
//或者,将其全局安装以使用qrcode命令行来保存qrcode图像或生成可在终端中查看的图像。
npm install -g qrcode
Usage: qrcode [options]
QR Code options:
-v, --version QR Code symbol version (1 - 40)
-e, --error Error correction level [choices: "L", "M", "Q", "H"]
-m, --mask Mask pattern (0 - 7)
Renderer options:
-t, --type Output type [choices: "png", "svg", "utf8"]
-w, --width Image width (px)
-s, --scale Scale factor
-q, --qzone Quiet zone size
-l, --lightcolor Light RGBA hex color
-d, --darkcolor Dark RGBA hex color
Options:
-o, --output Output file
-h, --help Show help [boolean]
Examples:
qrcode "some text" Draw in terminal window
qrcode -o out.png "some text" Save as png image
qrcode -d F00 -o out.png "some text" Use red as foreground color
// index.js -> bundle.js
var QRCode = require('qrcode')
var canvas = document.getElementById('canvas')
QRCode.toCanvas(canvas, 'sample text', function (error) {
if (error) console.error(error)
console.log('success!');
})
var QRCode = require('qrcode')
QRCode.toDataURL('I am a pony!', function (err, url) {
console.log(url)
})
//可以使用Promises和Async / Await来代替回调函数。
import QRCode from 'qrcode'
// 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)
}
}