一、使用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,具體代碼如下:
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;
}
參考:
https://github.com/jeromeetienne/jquery-qrcode
http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt