卵を SVG で描画しました。卵の方程式を利用しています。今回も Snap.svg を使いました。
Snap.svg ライブラリと JavaScript のソースファイルを指定します。
<script src="js/snap.svg-min.js"></script> <script src="js/egg01.js"></script>
実行結果のところには "svg" という id の svg 要素に rect 要素を準備し、 生成されたコードとして pre 要素を用意しました。 中身は egg01.js の中で更新、追加しています。
<h2>実行結果</h2> <svg id="svg" xmlns="http://www.w3.org/2000/svg" width="640" height="400"> <rect x="0" y="0" width="640" height="400" style="fill:#999"/> </svg> <h3>生成されたコード</h3> <ul> <li>2行目:egg01.html のソースに元々あった rect 要素です。</li> <li>3行~:Snap.svg ライブラリで追加した卵の SVG です。</li> </ul> <pre id="code" class="brush: xml; class-name: 'code'; highlight: [2,3]"> </pre>
卵の方程式で卵を描いて、それを回転させるプログラムです。
const width = 640; const height = 400; const ox = width / 2; const oy = height / 2; const scale = 170; let s; // for Snap let egg; let angle = 0; /** * rotateEgg function * @since 0.1 */ const rotateEgg = function() { angle += 15; if (360 <= angle) angle -= 360; egg.transform('rotate(' + angle + ' ' + ox + ' ' + oy + ')'); } /** * drawGrids function * @since 0.1 */ const drawGrids = function() { y1 = oy - (-1.0) * scale; y2 = oy - 1.0 * scale; for (x = -1.0; x <= 1.0; x += 0.1) { if (Math.round(x * 10) % 10 == 0) w = 2; else w = 1; x1 = ox + Math.round(x * scale); s.line(x1, y1, x1, y2).attr({stroke: '#ccc', strokeWidth: w}); } x1 = ox + -1.0 * scale; x2 = ox + 1.0 * scale; for (y = -1.0; y <= 1.0; y += 0.1) { if (Math.round(y * 10) % 10 == 0) w = 2; else w = 1; y1 = oy - Math.round(y * scale); s.line(x1, y1, x2, y1).attr({stroke: '#ccc', strokeWidth: w}); } } /** * onload function * @since 0.1 */ window.onload = function() { // Get svg element s = Snap('#svg'); drawGrids(); // Draw an egg with egg equations const a = 0.5; const b = 0.37; let points = ''; Δθ = Math.PI / 32; for (θ = -Math.PI; θ <= Math.PI; θ += Δθ) { x = a * Math.cos(θ); y = b * Math.cos(θ / 4) * Math.sin(θ); points += (ox + x * scale).toFixed(1); points += ','; points += (oy - y * scale).toFixed(1); if (θ + Δθ <= Math.PI) points += ' '; } egg = s.polygon(points).attr({fill: 'moccasin', stroke: 'gray', strokeWidth: 2}); // 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'); setInterval(rotateEgg, 1000); }
このプログラムは以下の情報またはソフトウェアを参照しています。