3
1

JavaScriptでQRコードからSVGファイルを作成する

Last updated at Posted at 2024-03-31
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/qrcode@1.4.4/build/qrcode.min.js"></script>
  </head>

  <body>
    <p style="font-size: 32px;">QRコードからSVGファイルを作成します</p>
    <input type="text" id="inputText" />
    <button onclick="generateQRCode()">QRコード生成</button>
    <div id="qrcode"></div>
    <a id="downloadLink" style="display: none;">SVGファイルをダウンロード</a>
    <script>
      async function generateQRCode() {
        const inputText = $("#inputText").val();
        const options = {
          type: 'svg',
          // width: 256,
          margin: 2,
          color: {
            dark: '#000',
            light: '#fff'
          }
        };
        const svgTag = await QRCode.toString(inputText, options);
        console.log(svgTag)
        $("#qrcode").empty().append(svgTag);
        $("#qrcode svg").attr("width", "256px");
        const fileName = "";
        const downloadLink = document.getElementById("downloadLink");
        downloadLink.href = "data:image/svg+xml;charset=utf-8," + encodeURIComponent(svgTag);
        downloadLink.download = fileName;
        downloadLink.style.display = "inline"; // displayをinlineに変更
      }
    </script>
  </body>
</html>

jsDelivr

Browser
node-qrcode can be used in browser through module bundlers like Browserify and Webpack or by including the precompiled bundle present in build/ folder.

ブラウザからCDNで利用する時は、buildフォルダのファイルを指定する

参考

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1