QRCode.js
QRCode.js 是一个生成二维码的javascript库,通过操作dom标签和H5的 Canvas绘制。
基本使用
- 下载
下载地址:https://github.com/davidshimjs/qrcodejs - 引入
// 引入 QRCode.js
<script src="./qrcodejs/qrcode.js"></script>
3 . 创建元素
// 创建一个展示二维码的元素
<div id="qrcode"></div>
- 调用
// 简单方式
new QRCode(document.getElementById('qrcode'), 'your content');
// new QRCode 参数说明 new QRCode(element, option)
// element: 显示二维码的元素或元素ID
// option : 参数配置
// option 参数说明 如下表格
// 设置参数方式
var qrcode = new QRCode('qrcode', {
text: 'your content',
width: 256,
height: 256,
colorDark : '#000000',
colorLight : '#ffffff',
correctLevel : QRCode.CorrectLevel.H
});
option 参数说明
名称 | 默认值 | 说明 |
---|---|---|
width | 256 | 图像宽 |
height | 256 | 图像高 |
typeNumber | 4 | |
colorDark | “#000000” | 前景色 |
colorLight | “#ffffff” | 背景色 |
correctLevel | QRCode.CorrectLevel.L | 容错级别,可设置为:QRCode.CorrectLevel.L QRCode.CorrectLevel.M QRCode.CorrectLevel.Q QRCode.CorrectLevel.H |
-
API
- qrcode.makeCode(text) 设置二维码内容
- qrcode.clear() 清除二维码 清除二维码。(仅在不支持 Canvas 的浏览器下有效)
-
完整代码
// html
<div id="qrcode"></div>
// javascript
<script src="./qrcodejs/qrcode.js"></script>
<script>
// 调用
generateQRCode(data.wxQrCodeLoginUrl, 130, 'qrcode');
// 封装生成二维码方法
function generateQRCode(QRValue, QRSize, QRElementNode) {
//step1.初始化二维码对象
var codeObj = new QRCode(QRElementNode, {
text: QRValue,
width: QRSize,
height: QRSize,
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.H
});
//step2根据目标数据画出二维码
if ("" != QRValue) {
codeObj.clear();
codeObj.makeCode(QRValue);
}
}
</script>