jquery.qrcode 預設僅支援 ASCII,中文需先轉 UTF-8 編碼再傳入。本文提供完整轉碼函數 utf16to8 及整合示例。
function utf16to8(str) {
var out = '', i, len = str.length, c;
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 & 0x3F));
} else {
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
out += String.fromCharCode(0x80 | (c & 0x3F));
}
}
return out;
}
<div id="output"></div>
<script src="jquery.js"></script>
<script src="jquery.qrcode.min.js"></script>
<script>
$(function() {
$('#output').qrcode({
text: utf16to8('今天天氣不錯'),
width: 128,
height: 128,
render: 'canvas' // 或 'table' 兼容老瀏覽器
});
});
</script>
encodeURIComponent(str) 獲取 UTF-8 字串,再傳給 qrcode(需庫支援 UTF-8 字串)。jquery.qrcode 內部採用 canvas 或 table 渲染,canvas 效能更好、體積更小。canvas.toDataURL() 導出圖片供下載。