Pattern 0.1

青海波(せいがいは)のパターンのSVGを描くプログラムを作りました。 今回も Snap.svg を使いました。

実行結果

生成されたコード


      

ソース


pattern01.html

Snap.svg ライブラリと JavaScript のソースファイルを指定します。

  <script src="js/snap.svg-min.js"></script>
  <script src="js/pattern01.js"></script>

実行結果のところには "Pattern" という id の svg 要素と "code" という id の pre 要素を用意しました。 中身は pattern01.js の中で更新、追加しています。

今回の svg 要素は、背景色のみを rect 要素で塗っておき、パターンは Snap.svg ライブラリを使って描きました。

      <h2>実行結果</h2>
      <svg id="Pattern" xmlns="http://www.w3.org/2000/svg" width="640" height="400">
        <rect x="0" y="0" width="640" height="400" style="fill:#fff" />
      </svg>
      <h3>生成されたコード</h3>
      <ul>
        <li>2行目:元々ソースにあった rect 要素です。</li>
        <li>3行~:Snap.svg ライブラリで追加したパターンの SVG です。</li>
      </ul>
      <pre id="code" class="brush: xml; class-name: 'code'; highlight: [2,3]">
</pre>

pattern01.js

青海波(せいがいは)のパターンを表示するプログラムです。

const width = 640;
const height = 400;
let s;              // for Snap

const size = 60;
const dr = size * 0.1;

/**
 * drawWave function
 * @since 0.1
 */
const drawWave = function(x, y) {
    for (i = 0; i < 4; i++) {
        s.path(Snap.format('M{x1},{y1}A{rx},{ry} 0 0 1 {x2},{y2}', {
            x1: x + i * dr,
            y1: y + size / 2,
            rx: size / 2 - i * dr,
            ry: size / 2 - i * dr,
            x2: x + (size - i * dr),
            y2: y + size / 2
        })).attr({
            stroke: 'teal',
            strokeWidth: size * 0.04,
            fill: 'white'
        });
    }
}

/**
 * onload function
 * @since 0.1
 */
window.onload = function() {
    // Get svg element
    s = Snap('#Pattern');
    // Draw waves
    x0 = 0;
    for (y = -size / 2; y < height; y += size / 2 * (1 - Snap.sin(30))) {
        for (x = x0; x < width; x += size * Snap.cos(30)) {
            drawWave(x, y);
        }
        if (x0 == 0) {
            x0 = -size / 2 * Snap.cos(30);
        } else {
            x0 = 0;
        }
    }
    // Get generated SVG code
    let svgText = s.toString();
    // Show the code with additional new lines
    let codeNode = document.getElementById('code');
    codeNode.textContent = svgText.replace(/><([^/])/g, '>\n<$1');
}

参考文献

このプログラムは以下の情報またはソフトウェアを参照しています。