2018年1月24日 星期三

(JS)使用jquery-qrcode生成二維碼


先簡單說一下jquery-qrcode,這個開源的library(可以從https://github.com/jeromeetienne/jquery-qrcode 獲取),
qrcode.js 是實現二維碼數據計算的核心類,
jquery.qrcode.js 是把它用jquery方式封裝起來的,用它來實現圖形渲染,其實就是畫圖(支持canvas和table兩種方式)
支持的功能主要有:


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" //前景顏色   

使用方式非常簡單

Js代碼  
  1. jQuery( '#o​​utput' ).qrcode({width:200,height:200,correctLevel:0,text:content});  

 經過簡單實踐,
使用canvas方式渲染性能還是非常不錯的,但是如果用table方式,性能不太理想,特別是IE9以下的瀏覽器,所以需要自行優化一下渲染table的方式,這裡就不細述了。

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. }  


0 意見: