js生成二维码
1.安装qrcode
//在项目文件夹中执行: npm install --save qrcode //或者,将其全局安装以使用qrcode命令行来保存qrcode图像或生成可在终端中查看的图像。 npm install -g qrcode
2.用法
- CLI
Usage: qrcode [options] <input string> 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.html --> <html> <body> <canvas id="canvas"></canvas> <script src="bundle.js"></script> </body> </html> // 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!'); })
- nodejs使用
var QRCode = require('qrcode') QRCode.toDataURL('I am a pony!', function (err, url) { console.log(url) })
- es6/es7
//可以使用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) } }