要在純前端產生 QR Code,jquery.qrcode 是個輕巧的選擇。不過它原生只吃 byte 模式,直接傳中文會產生亂碼,需要多做一層編碼轉換。
QR Code 的 byte 模式是以單字節為單位寫入資料,而 JavaScript 字串是 UTF-16。中文字元直接丟進去會超過 0xFF 範圍,導致內容被截斷。解法是先把 UTF-16 字串轉成 UTF-8 位元組序列。
function utf16to8(str) {
var out = "", i, len, c;
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 src="jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="jquery.qrcode.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
jQuery('#output').qrcode(utf16to8("今天天氣不錯"));
});
</script>
<body>
<div id="output"></div>
</body>
qrcode() 接受物件形式的設定,除了文字內容外還能調整輸出的呈現方式與容错等級:
$('#output').qrcode({
render: "canvas", // canvas 或 table(table 模式相容性更好)
width: 256,
height: 256,
correctLevel: 2, // 0~3,數字越大容错越高但圖形越密
background: "#ffffff",
foreground: "#000000",
text: utf16to8("今天天氣不錯")
});
如果目標環境包含舊版瀏覽器,把 render 設為 table 會比 canvas 安全。另外,jquery.qrcode.min.js 本體已內建完整的 Reed-Solomon 錯誤更正與掩模評估演算法,不需另外準備任何資源,只要按上述方式引入即可運作。