使用jquery-qrcode生成二維碼

1、使用jquery-qrcode生成二維碼

先簡單說一下jquery-qrcode,這個開源的三方庫(能夠從https://github.com/jeromeetienne/jquery-qrcode 獲取),javascript

qrcode.js 是實現二維碼數據計算的核心類,java

jquery.qrcode.js 是把它用jquery方式封裝起來的,用它來實現圖形渲染,其實就是畫圖(支持canvas和table兩種方式)jquery

 

支持的功能主要有:git

 

Js代碼   收藏代碼
  1. text     : "https://github.com/jeromeetienne/jquery-qrcode"  //設置二維碼內容  

 

Js代碼   收藏代碼
  1. render   : "canvas",//設置渲染方式  
  2. width       : 256,     //設置寬度  
  3. height      : 256,     //設置高度  
  4. typeNumber  : -1,      //計算模式  
  5. correctLevel    : QRErrorCorrectLevel.H,//糾錯等級  
  6. background      : "#ffffff",//背景顏色  
  7. foreground      : "#000000" //前景顏色  

 

使用方式很是簡單github

 

Js代碼   收藏代碼
  1. jQuery('#output').qrcode({width:200,height:200,correctLevel:0,text:content});  

 

 通過簡單實踐,canvas

 

使用canvas方式渲染性能仍是很是不錯的,可是若是用table方式,性能不太理想,特別是IE9如下的瀏覽器,因此須要自行優化一下渲染table的方式,這裏就不細述了。瀏覽器

 

2、JS生成中文二維碼

其實上面的js有一個小小的缺點,就是默認不支持中文。性能

這跟js的機制有關係,jquery-qrcode這個庫是採用 charCodeAt() 這個方式進行編碼轉換的,優化

而這個方法默認會獲取它的 Unicode 編碼,通常的解碼器都是採用UTF-8, ISO-8859-1等方式,編碼

英文是沒有問題,若是是中文,通常狀況下Unicode是UTF-16實現,長度2位,而UTF-8編碼是3位,這樣二維碼的編解碼就不匹配了。

解決方式固然是,在二維碼編碼前把字符串轉換成UTF-8,具體代碼以下:

 

Js代碼   收藏代碼
  1. function utf16to8(str) {  
  2.     var out, i, len, c;  
  3.     out = "";  
  4.     len = str.length;  
  5.     for(i = 0; i < len; i++) {  
  6.     c = str.charCodeAt(i);  
  7.     if ((c >= 0x0001) && (c <= 0x007F)) {  
  8.         out += str.charAt(i);  
  9.     } else if (c > 0x07FF) {  
  10.         out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));  
  11.         out += String.fromCharCode(0x80 | ((c >>  6) & 0x3F));  
  12.         out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));  
  13.     } else {  
  14.         out += String.fromCharCode(0xC0 | ((c >>  6) & 0x1F));  
  15.         out += String.fromCharCode(0x80 | ((c >>  0) & 0x3F));  
  16.     }  
  17.     }  
  18.     return out;  
  19. }  

 

參考:

https://github.com/jeromeetienne/jquery-qrcode

http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt

相關文章
相關標籤/搜索