星期三, 7月 22, 2026

[GAS] 使用 JavaScript Library 來產生 QRCode

在 GAS 上使用 JavaScript Linrary - Kjua 來產生 QRCode

code.gs
function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index')
    .setTitle('kjua QRCode 產生器');
}

Index.html
<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <!-- 引入 kjua CDN -->
    <script src="https://cdn.jsdelivr.net/npm/kjua@0.10.0/dist/kjua.min.js"></script>
    <style>
      body {
        font-family: Arial, sans-serif;
        text-align: center;
        padding: 40px 20px;
      }
      input {
        padding: 10px;
        font-size: 16px;
        width: 80%;
        max-width: 300px;
        margin-bottom: 10px;
      }
      button {
        padding: 10px 20px;
        font-size: 16px;
        background-color: #4CAF50;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
      }
      button:hover {
        background-color: #45a049;
      }
      #qrcode-container {
        margin-top: 30px;
      }
    </style>
  </head>
  <body>
    
    <h2>QRCode 產生器</h2>
    <input type="text" id="text-input" value="https:/www.google.com" placeholder="請輸入要轉換的網址或文字" />
    <br>
    <button onclick="generateQRCode()">產生 QRCode</button>
    
    <!-- QRCode 渲染區域 -->
    <div id="qrcode-container"></div>

    <script>
      function generateQRCode() {
        const textToEncode = document.getElementById('text-input').value;
        const container = document.getElementById('qrcode-container');
        
        // 避免重覆產生 QRCode,每次都先清空
        container.innerHTML = ""; 

        if (!textToEncode) {
          alert("請輸入內容!");
          return;
        }

        // 呼叫 kjua 並產生 QRCode
        const qrCodeElement = kjua({
          render: 'image',   // 渲染為 <img> 標籤
          text: textToEncode,
          size: 250,         // 尺寸設定為 250px
          fill: '#000000',   // QRCode 顏色
          back: '#ffffff',   // 背景顏色
          rounded: 10        // 模組圓角 (0-100),讓外觀看起來更柔和
        });

        container.appendChild(qrCodeElement);
      }
    </script>
    
  </body>
</html>

沒有留言:

張貼留言