想在前端把一段文字(可以是中文)即時生成 QR Code 圖片嗎?透過 jquery.qrcode 這個外掛就能辦到。要注意的是,如果要在 QR Code 中央加上 logo,logo 千萬別太大,否則會導致掃描不出內容。
完整程式碼如下:
<html>
<head>
<title></title>
<script src="js/jquery-1.8.3.js" type="text/javascript"></script>
<script src="js/qrcode.js" type="text/javascript"></script>
<script src="js/jquery.qrcode.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
$("#bt").bind("click", function () {
text = $("#text").val();
$("#div_div").qrcode(utf16to8(text));
})
})
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;
}
</script>
</head>
<body>
<input type="text" id="text" />
<input type="button" value="生成" id="bt" />
<div id="div_div" style="width:400px;height:400px;border:1px solid #000;"></div>
</body>
</html>
這裡一共引用了三支 js:一支是 jQuery(版本不拘),另外兩支 qrcode.js 與 jquery.qrcode.js 則是負責繪製 QR Code 的核心。由於 QR Code 編碼時對中文支援有限,程式中特別寫了一個 utf16to8 函數先把中文轉成 UTF-8,再交給 qrcode 方法繪製,這樣中文內容才能正確還原。