昔、Canvas に描いた「の」の字を SVG.js で描いてみました。
<script type="text/javascript" src="js/svg.min.js"></script> <script type="text/javascript" src="js/no01.js"></script>実行結果のところには "svg" という id の div 要素と "code" という id の pre 要素を用意しました。中身は svg05.js の中で作って入れます。
<h2>実行結果</h2> <div id="svg"> </div> <h3>生成されたコード</h3> <pre id="code" class="brush: xml; class-name: 'code'"> </pre>
canvas に描画したときとの大きな違いは、円弧を描くときに SVG の場合は通過点の座標を計算する必要があることです。 始点を (x1,y1)、左下の角を (x2,y2)、終点を (x3,y3) として計算しました。
window.onload = function() { // Generate svg element //<svg width="300" height="300" style="background-color: cyan"> const r = 100; // radius const c = 150; // center var draw = SVG().addTo('#svg').size(300, 300).css('background-color', 'cyan'); var a = Math.PI / 3 - 0.2; var dx = r * Math.cos(a); var dy = r * Math.sin(a); var x1 = c + Math.round(dx); var y1 = c - Math.round(dy); dx = r * Math.cos(a); dy = r * Math.sin(a); var x2 = c - Math.round(dx); var y2 = c + Math.round(dy); a = Math.PI / 3; dx = r * Math.cos(a); dy = r * Math.sin(a); var x3 = c + Math.round(dx); var y3 = c + Math.round(dy); // <path d="M216 75, // L84 225, // A100 100, 0, 1, 1, 200 237" // style="fill:none;stroke:#000;stroke-width:50"/> draw.path(`M${x1} ${y1}, L${x2} ${y2} A${r} ${r}, 0, 1, 1, ${x3} ${y3}`).fill('none').stroke({color: '#000', width: 50}); //</svg> var svgNode = document.getElementById('svg').children[0]; var codeNode = document.getElementById('code'); // Get generated SVG code var svgText = new XMLSerializer().serializeToString(svgNode); // Show the code with additional new lines codeNode.textContent = svgText.replace(/></g, '>\n<'); }
このプログラムは以下の情報またはソフトウェアを参照しています。