文章出處

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

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

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

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

支持的功能主要有: 

  • text     : "https://github.com/jeromeetienne/jquery-qrcode"  //設置二維碼內容  
  • render   : "canvas",//設置渲染方式  
  • width       : 256,     //設置寬度  
  • height      : 256,     //設置高度  
  • typeNumber  : -1,      //計算模式  
  • correctLevel    : QRErrorCorrectLevel.H,//糾錯等級  
  • background      : "#ffffff",//背景顏色  
  • foreground      : "#000000" //前景顏色   

使用方式非常簡單 

  • jQuery('#output').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,具體代碼如下:

  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


文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()