矢絣(やがすり)のパターンのSVGを描くプログラムを作りました。 今回も Snap.svg を使いました。
Snap.svg ライブラリと JavaScript のソースファイルを指定します。
<script src="js/snap.svg-min.js"></script> <script src="js/pattern03.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:white" /> </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>
矢絣のパターンを表示するプログラムです。
let s; // for Snap let width; let height; const fw = 80; // feathers width const fh = 80; // feathers height /** * drawFeathers function * @since 0.3 */ const drawFeathers = function(x, y) { s.rect(x + fw * 0.225, y, fw * 0.05, fh * 0.25).attr({stroke: 'none', fill: 'purple'}); s.path(Snap.format('M{x1},{y1}L{x2},{y2} {x3},{y3} {x4},{y4}Z', { x1: x, y1: y, x2: x, y2: y + fh, x3: x + fw * 0.225, y3: y + fh, x4: x + fw * 0.225, y4: y + fh * 0.25 })).attr({stroke: 'none', fill: 'purple'}); s.path(Snap.format('M{x1},{y1}L{x2},{y2} {x3},{y3} {x4},{y4}Z', { x1: x + fw * 0.5, y1: y, x2: x + fw * 0.5, y2: y + fh, x3: x + fw * 0.275, y3: y + fh, x4: x + fw * 0.275, y4: y + fh * 0.25 })).attr({stroke: 'none', fill: 'purple'}); s.path(Snap.format('M{x1},{y1}L{x2},{y2} {x3},{y3}Z', { x1: x + fw * 0.5, y1: y, x2: x + fw * 0.725, y2: y, x3: x + fw * 0.725, y3: y + fh * 0.25 })).attr({stroke: 'none', fill: 'purple'}); s.path(Snap.format('M{x1},{y1}L{x2},{y2} {x3},{y3}Z', { x1: x + fw, y1: y, x2: x + fw * 0.775, y2: y, x3: x + fw * 0.775, y3: y + fh * 0.25 })).attr({stroke: 'none', fill: 'purple'}); s.rect(x + fw * 0.725, y + fh * 0.25, fw * 0.05, fh * 0.75).attr({stroke: 'none', fill: 'purple'}); } /** * onload function * @since 0.3 */ 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 += fh) { for (x = x0; x <= width; x += fw) { drawFeathers(x, y); } if (x0 == 0) { x0 = -fw / 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; }
このプログラムは以下の情報またはソフトウェアを参照しています。