先日携わったツール開発でQRコードを生成する必要があり、その際に導入したのでメモ。

qr-code-styling.js

Denys Kozakさん による QR Code Styling にてQRコードを生成します。

本家はこちら ( QR Code Styling ) です。

読み込む

使用には、CDN経由で読み込むか、npmでインストールするなどします。

今回は、とりあえずscriptタグで読み込むので、以下はその例。

<script type="text/javascript" id="qr-code-styling" src="https://unpkg.com/qr-code-styling@1.5.0/lib/qr-code-styling.js?ver=0.0.1"></script>

WordPressの場合はfunctions.phpへ以下を追記。

wp_enqueue_script( 'qr-code-styling', 'https://unpkg.com/qr-code-styling@1.5.0/lib/qr-code-styling.js', array(), '0.0.1', true );

とりあえず出力

とりあえず、色々と設定して出力してみる。
中央のロゴ(画像)はお好きな画像のURLを記載してください。不要なら削除で。

コード|HTML

<style>
/* 表示調整用 */
#qr-code {
    width: 100%;
}
#qr-code > * {
    display: block;
    width: 100%;
    max-width: 30rem;
    margin: 0 auto;
}
</style>

<div id="qr-code"><!-- ここにQRコードが生成される --></div>

<script type="text/javascript" id="qr-code-styling" src="https://unpkg.com/qr-code-styling@1.5.0/lib/qr-code-styling.js?ver=0.0.1"></script>
<script>
    let target = document.getElementById("qr-code");
    let url = "https://asaoka.site/";

    const QR = new QRCodeStyling({
        width: 1280,
        height: 1280,
        margin: 50,
        type: "canvas",
        data: url,
        image: "https://asaoka.site/*****/a-no-logo@gray.png",
        dotsOptions: {
            color: "rgb(65, 65, 65)",
            type: "rounded"
        },
        cornersSquareOptions: {
            type: "extra-rounded"
        },
        backgroundOptions: {
            color: "#fff",
        },
        imageOptions: {
            crossOrigin: "anonymous",
            margin: 30
        }
    });
    QR.append(target);
</script>

出力結果

おお~、簡単!

主なオプションは以下。公式より抜粋させてもらいます。より詳細なオプション等は以下のリンクよりご確認ください。

  • オプション
  • タイプ
  • 説明
  • width
  • number(デフォルトは300)
  • canvasのサイズ(横方向)
  • height
  • number(デフォルトは300)
  • canvasのサイズ(縦方向)
  • type
  • string
  • レンダリングされる要素のタイプ
    ‘canvas’ もしくは ‘svg’ を指定
  • data
  • string
  • QRコードを読み取り後に開かれるURL
  • image
  • string
  • QRコードの中央に配置する画像パス(URL)
  • margin
  • number
  • canvas周囲の余白
  • qrOptions
  • object
  • QRコードの生成オプション
  • dotsOptions
  • object
  • QRコードのドットスタイルオプション
    色変更は color オプション、スタイルは style オプションから ‘rounded’ ‘dots’ ‘classy’ ‘classy-rounded’ ‘square’ ‘extra-rounded’ いずれかを指定
  • cornersSquareOptions
  • object
  • 隅に配置される大きい四角形のオプション
    色変更は color オプション、スタイルは style オプションから ‘dot’ ‘square’ ‘extra-rounded’ いずれかを指定
  • backgroundOptions
  • object
  • 背景色オプション色変更は color オプションから指定
GitHub – kozakdenys/qr-code-styling: Automaticly generate your styled QR code in your web app.

参考

QR Code Styling

GitHubのQRコードを生成するサービスを作ったよ