Pattern 0.2

麻(あさ)の葉のパターンのSVGを描くプログラムを作りました。 今回も Snap.svg を使いました。

実行結果

生成されたコード


      

ソース


pattern02.html

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

  <script src="js/snap.svg-min.js"></script>
  <script src="js/pattern02.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:olive" />
      </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>

pattern02.js

麻の葉のパターンを表示するプログラムです。

let s;                  // for Snap
let width;
let height;

const sqrt3 = Math.sqrt(3);
const lw = 50;          // leaf width
const lh = 25 * sqrt3;  // leaf height

/**
 * drawLeaf function
 * @since 0.2
 */
const drawLeaf = function(x, y) {
    s.line(x, y, x + lw, y).attr({stroke: 'white', strokeWidth: lw * 0.04});
    s.line(x + lw / 2, y, x + lw / 2, y + (sqrt3 - 0.5) / sqrt3 * lh).attr({stroke: 'white', strokeWidth: lw * 0.04});
    s.line(x, y + 0.5 / sqrt3 * lh, x, y + lh).attr({stroke: 'white', strokeWidth: lw * 0.04});
    s.line(x + lw / 2, y, x, y + lh).attr({stroke: 'white', strokeWidth: lw * 0.04});
    s.line(x + lw / 2, y, x + lw, y + lh).attr({stroke: 'white', strokeWidth: lw * 0.04});
    s.line(x + lw / 2, y, x, y + 0.5 / sqrt3 * lh).attr({stroke: 'white', strokeWidth: lw * 0.04});
    s.line(x + lw / 2, y, x + lw, y + 0.5 / sqrt3 * lh).attr({stroke: 'white', strokeWidth: lw * 0.04});
    s.line(x + lw / 2, y + (sqrt3 - 0.5) / sqrt3 * lh, x, y + lh).attr({stroke: 'white', strokeWidth: lw * 0.04});
    s.line(x + lw / 2, y + (sqrt3 - 0.5) / sqrt3 * lh, x + lw, y + lh).attr({stroke: 'white', strokeWidth: lw * 0.04});
}

 /**
  * onload function
  * @since 0.2
  */
 window.onload = function() {
     // Get svg element
     s = Snap('#Pattern');
     width = s.getBBox().width;
     height = s.getBBox().height;
     // Draw leaves
     x0 = 0;
    for (y = 0; y <= height; y += lh) {
        for (x = x0; x <= width; x += lw) {
            drawLeaf(x, y);
        }
        if (x0 == 0) {
            x0 = -lw / 2;
        } else {
            x0 = 0;
        }
    }
    // Get generated SVG code
    let svgText = s.toString();
    // Add new lines
    svgText = svgText.replace(/><([^/])/g, '>\n<$1');
    svgText = svgText.replace(/<\/svg>/, '\n$&');
    // Show the code
    let codeNode = document.getElementById('code');
    codeNode.textContent = svgText;
}

参考文献

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