使用jquery.qrcode生成二維碼及常見問題解決方案

 

轉載文章  使用jquery.qrcode生成二維碼及常見問題解決方案javascript

 

1、jquery.qrcode.js介java

jquery.qrcode.js 是一個純瀏覽器 生成 QRcode 的 jQuery 插件((能夠從https://github.com/jeromeetienne/jquery-qrcode 獲取)),它使用很是簡單,生成的 QRcode 無需下載圖片,而且不依賴第三方服務,插件壓縮以後大小小於 4K。jquery

 

2、參數說明git

 

text     : "https://github.com/jeromeetienne/jquery-qrcode"  //設置二維碼內容 
 render : "canvas",//設置渲染方式 (有兩種方式 table和canvas,默認是canvas) 
 width : 256,     //設置寬度 
 height : 256,     //設置高度 
 typeNumber : -1,      //計算模式 
 correctLevel : 0,//糾錯等級 
 background : "#ffffff",//背景顏色 
 foreground : "#000000" //前景顏色 

 

3、jquery.qrcode使用github

 

1. 加載 jQuery 和 jquery.qrcode.js:canvas

<script type='text/javascript' src='http://cdn.staticfile.org/jquery/2.1.1/jquery.min.js'></script> 

<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:微信

最簡單方式: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瀏覽器中二維碼生成成功後沒法掃描解決方法:spa

//改爲使用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"});

 

3.jquery.qrcode生成二維碼內容不支持中文

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; 

 

相關文章
相關標籤/搜索