QRCode
用法
1.使用npm安裝到你的項目中 npm install qrcode2 --save
2. 使用commonjs或者es6模塊方式導入
var QRCode = require('qrcode2');
// 或者
import QRCode from 'qrcode2';
3 . 實例化QRCode對象
new QRCode(document.getElementById('qrcode'), 'http://www.baidu.com');
//
// 或者配置一些選項
var qrcode = new QRCode(document.getElementById("qrcode"), {
text: "http://www.baidu.com",
width: 128,
height: 128,
colorDark : "#000",
colorLight : "#fff",
correctLevel : QRCode.CorrectLevel.H
});
參數
參數 | 默認值 | 說明 | 備注 |
---|---|---|---|
text | string | 二維碼內容字符串 | 如果是url的話,為了微信和QQ可以識別,連接中的中文使用encodeURIComponent進行編碼 |
width | 256 | 圖像寬度 | 單位像素(百分比不行) |
height | 256 | 圖像高度 | 單位像素(百分比不行) |
colorDark | '#000' | 二維碼前景色 | 英文\十六進制\rgb\rgba\transparent都可以 |
colorLight | ‘#fff’ | 二維碼背景色 | 英文\十六進制\rgb\rgba\transparent都可以 |
correctLevel | QRCode.CorrectLevel.L | 容錯級別 | 由低到高 .L M Q H |
方法
clear:清除QR code
makeCode(text: String):重新繪制QR code (僅在不支持 Canvas 的瀏覽器下有效)
常見bug1 長字符串顯示模糊問題
-
問題原因:
顯示模糊的問題,是canvas的問題。由於字符串比較長,尤其是需要傳一個連接地址,后面還加一些參數的時候,就會加大二維碼的像素復雜度,而本身canvas在繪制的時候,就一直有像素模糊的問題,尤其是在手機上的時候 -
解決方法:
先將生成的二維碼進行倍數擴大,然后在css上面固定其顯示寬高,這樣就可以擴大顯示像素精度。
js放大
var qrcode = new QRCode(document.getElementById("qrcode"), {
text: "http://www.baidu.com",
width: 128 * 5, // 相應寬高擴大5倍
height: 128 * 5,
colorDark : "#000",
colorLight : "#fff",
correctLevel : QRCode.CorrectLevel.H
});
css固定寬高
可以給canvas 和 img 固定為 128* 128的大小
也可以在包裹#qrcode 的容器上固定128* 128的大小 里面內容100%
比如
.qrcode-out {
width: 128px;
height: 128px;
}
canvas,img {
width:100%;
height: 100%;}
常見bug2 因為url太長,導致二維碼加載報錯
一般報錯提醒 Error: code length overflow. (1756>1056)
一般都是容錯率設置為最高導致的,此時把容錯率調低一級便可以
correctLevel : QRCode.CorrectLevel.Q