1、jquery.qrcode.js介紹javascript
jquery.qrcode.js 是一個純瀏覽器 生成 QRcode 的 jQuery 插件((能夠從https://github.com/jeromeetienne/jquery-qrcode 獲取)),它使用很是簡單,生成的 QRcode 無需下載圖片,而且不依賴第三方服務,插件壓縮以後大小小於 4K。java
2、參數說明jquery
3、jquery.qrcode使用
git
1. 加載 jQuery 和 jquery.qrcode.js:github
<script type='text/javascript' src='http://cdn.staticfile.org/jquery/2.1.1/jquery.min.js'></script> canvas
<script type="text/javascript" src="http://cdn.staticfile.org/jquery.qrcode/1.0/jquery.qrcode.min.js"></script> 瀏覽器
2. 建立一個用於包含 QRcode 圖片的 DOM 元素,好比 div:微信
<div id="qrcode"></div> 編碼
3.經過下面代碼生成 QRcode:spa
最簡單方式:jQuery('#qrcode').qrcode("http://blog.csdn.net/mr_smile2014");
自定義方式:jQuery('#qrcode').qrcode({render:canvas,width: 64,height: 64,correctLevel:0,text: "http://blog.csdn.net/mr_smile2014"});
4、常見問題
1.在chorme瀏覽器中二維碼生成成功後沒法掃描解決方法:
//改爲使用table的渲染方式,親測支持各類各版本的瀏覽器
jQuery('#qrcode').qrcode({width: 200,height: 200,correctLevel:0,render: "table",text: "http://blog.csdn.net/mr_smile2014"});
2.在微信或手機瀏覽器中生成的二維碼沒法掃描解決方法;
//改爲使用默認的渲染方式,支持微信和QQ內置瀏覽器及其它手機瀏覽器
jQuery('#qrcode').qrcode({width: 200,height: 200,correctLevel:0,text: "http://blog.csdn.net/mr_smile2014"});
jquery-qrcode這個庫是採用 charCodeAt() 這個方式進行編碼轉換的,這個方法默認會獲取它的 Unicode 編碼,通常的解碼器都是採用UTF-8, ISO-8859-1等方式。
英文是沒有問題,若是是中文,通常狀況下Unicode是UTF-16實現,長度2位,而UTF-8編碼是3位,這樣二維碼的編解碼就不匹配了。
解決方式固然是,在二維碼編碼前把字符串轉換成UTF-8,具體代碼以下:
jQuery('#qrcode').qrcode({width: 200,height: 200,correctLevel:0,text: utf16to8("jquery-qrcode竟然不支持中文,太可恨了!")});
function utf16to8(str) {
var out, i, len, c;
out = "";
len = str.length;
for(i = 0; i < len; i++) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
out += str.charAt(i);
} else if (c > 0x07FF) {
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return out;
}
3.jquery.qrcode生成二維碼內容不支持中文