1、先簡單說一下jquery-qrcode,這個開源的三方庫(可以從https://github.com/jeromeetienne/jquery-qrcode 獲取),
qrcode.js 是實現二維碼數據計算的核心類,
jquery.qrcode.js 是把它用jquery方式封裝起來的,用它來實現圖形渲染,其實就是畫圖(支持canvas和table兩種方式)
效果圖:
支持的功能主要有:
content : "http://www.baidu.com" //設置二維碼鏈接
其他默認參數:
render : "canvas",//設置渲染方式 width : 256, //設置寬度 height : 256, //設置高度 typeNumber : -1, //計算模式 correctLevel : QRErrorCorrectLevel.H,//糾錯等級 background : "#ffffff",//背景顏色 foreground : "#000000" //前景顏色
使用方式非常簡單->demo:1、引入jquery(毫無疑問)2、分別引入jquery.qrcode.js和qrcode.js 3、使用div,$("#qrcode").qrcode("http://www.baidu.com");
<html> <head> <title>JS前端qrcode生成二維碼</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <script type="text/javascript" src="jquery-1.10.1.min.js"></script> <script type="text/javascript" src="jquery.qrcode.js"></script> <script type="text/javascript" src="qrcode.js"></script> </head> <body> <div id="qrcode"></div> <script type="text/javascript"> $("#qrcode").qrcode({width:200,height:200,correctLevel:0,text:"http://www.baidu.com"}); </script> </body> </html>
TIPS:默認使用canvas方式渲染性能還是非常不錯的。
二、支持中文二維碼
其實上面的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; }
