萬盛學電腦網

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

jQuery 生成 QR Code(含中文支援)完整範例

效果展示

輸入文字(含中文),點擊按鈕即時生成 QR Code 圖片(Canvas/Table 渲染)。

所需檔案

  • jquery-1.8.3.js(或任意 1.7+ 版本)
  • qrcode.js(核心編碼庫)
  • jquery.qrcode.js(jQuery 包裝)

完整 HTML + JS 範例

<html xmlns="https://www.w3.org/1999/xhtml">
<head>
  <title>QR Code Generator</title>
  <script src="js/jquery-1.8.3.js"></script>
  <script src="js/qrcode.js"></script>
  <script src="js/jquery.qrcode.js"></script>
  <script>
  $(function() {
    $("#bt").on("click", function() {
      var text = $("#text").val();
      // 必須先將 UTF-16 字串轉為 UTF-8 位元流,qrcode.js 才能正確編碼中文
      $("#div_div").qrcode(utf16to8(text));
    });
  });

  // 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 & 0x3F));
      } else {
        out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
        out += String.fromCharCode(0x80 | (c & 0x3F));
      }
    }
    return out;
  }
  </script>
</head>
<body>
  <input type="text" id="text" placeholder="輸入文字或中文" />
  <input type="button" value="生成 QR Code" id="bt" />
  <div id="div_div" style="width:400px;height:400px;border:1px solid #000;"></div>
</body>
</html>

加入 Logo 的提示

生成 QR Code 後,可在 #div_div 內用絕對定位疊加一個小 Logo 圖片(建議 ≤ 30×30px),過大會導致掃描失敗。也可使用支援 Logo 內嵌的進階庫(如 qrcodejs 的 logo 選項)。

copyright © 萬盛學電腦網 all rights reserved