萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jquery.qrcode 生成支援中文的二維碼

jquery.qrcode 預設僅支援 ASCII,中文需先轉 UTF-8 編碼再傳入。本文提供完整轉碼函數 utf16to8 及整合示例。

UTF-16 轉 UTF-8 函數

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>

注意事項

  • 若專案已使用 ES6,可直接用 encodeURIComponent(str) 獲取 UTF-8 字串,再傳給 qrcode(需庫支援 UTF-8 字串)。
  • jquery.qrcode 內部採用 canvas 或 table 渲染,canvas 效能更好、體積更小。
  • 生成後可用 canvas.toDataURL() 導出圖片供下載。
copyright © 萬盛學電腦網 all rights reserved