有些耗 CPU 的計算完全可以在客戶端完成,例如生成二維碼。qrcode 其實是透過計算,再使用 jQuery 實現圖形渲染與畫圖,支援 canvas 與 table 兩種方式生成二維碼。
qrcode 是 jQuery 組件,至少需要 jquery 與 jquery.qrcode 兩個 js 檔,可到 GitHub 獲取最新代碼。
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.qrcode.min.js"></script>
在頁面上需要顯示二維碼的地方加入一個空元素(此處用 div):
<div id="qrcode"></div>
在需要生成二維碼時,調用一下即可直接生成:
$("#qrcode").qrcode("https://www.cnblogs.com");//需要生成的頁面
render(預設 canvas):渲染方式,支援 canvas 和 table;width:寬度;height:高度;text:需要生成的 url。
例如:
$("#qrcode").qrcode({
render: "table",
width: 200,
height: 200,
text: "https://www.cnblogs.com"
});
實測發現無法識別含中文內容的二維碼。查閱資料後了解到,jquery-qrcode 採用 charCodeAt() 進行編碼轉換,而該方法預設會取得 Unicode 編碼,因此若有中文內容,需在生成二維碼前先把字串轉成 UTF-8。可透過以下函數轉換中文字串:
function toUtf8(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;
}
用前端畫出的二維碼不是 canvas 就是 table,要如何下載?我們只需把 canvas 的內容畫到 image 上再下載即可:
function download(canvasElem, filename, imageType) {
var event, saveLink, imageData, defalutImageType;
defalutImageType = 'png';//定義默認圖片類型
imageData = canvasElem.toDataURL(imageType || defalutImageType);//將 canvas 元素轉化為 image data
saveLink = document.createElementNS('https://www.w3.org/1999/xhtml', 'a');
saveLink.href = imageData;
saveLink.download = filename;
event = document.createEvent('MouseEvents');
event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
saveLink.dispatchEvent(event);
};
在 Angular 中使用時可封裝成 directive,但要確保已引入前面兩個 js 檔:
var appModule = angular.module('app', []);
appModule.directive('qrcode', function() {
return {
restrict: "A",
scope: {
text : '=',
options : '='
},
link: function(scope, elem, attrs) {
var $elem, options;
$elem = $(elem);
options = { //獲取元素的寬度和高度
width: $elem.width(),
height: $elem.height()
};
angular.extend(options, scope.options);
scope.$watch('text', function(newText) {
if (newText) {
options.text = newText;
$(elem).qrcode(options);//重新生成二維碼
}
});
};
};
});
下載方法在 Angular 中也可封裝成一個 service 使用。以上就是用 qrcode 生成二維碼的用法,希望對你的開發有所幫助。