11年前、この JavaScript の連載の第2回では canvas の API を利用して「の」の字を描画しました。そのときのコードが以下の内容です。fillRect() で背景色を塗りつぶし、直線と円弧をそれぞれ stroke() で描画しています。
window.onload = function() {
// キャンバスとコンテキスト取得
var canvas = document.querySelector('#no');
var context = canvas.getContext('2d');
// 塗りつぶし
context.fillStyle = 'cyan';
context.fillRect(0, 0, 300, 300);
// 線を引く
context.strokeStyle = 'black';
context.lineWidth = 50;
var r = 100; // 半径
var c = 150; // 中心
var a = Math.PI/3-0.2;
var dx = r*Math.cos(a);
var dy = r*Math.sin(a);
var x = c + Math.floor(dx);
var y = c - Math.floor(dy);
// (直線の部分)
context.beginPath();
context.moveTo(x, y);
dx = (r+23)*Math.cos(a);
dy = (r+23)*Math.sin(a);
x = c - Math.floor(dx);
y = c + Math.floor(dy);
context.lineTo(x, y);
context.stroke();
// (円弧の部分)
context.beginPath();
context.arc(c, c, r, Math.PI*2/3, Math.PI/3, false);
context.stroke();
};
今回は「の」の字を SVG.js で描いてみました。コードと結果はこちら。コードは以下にも掲載しておきます。css() で背景色を指定し、path() で直線と円弧を描画しています。
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<');
}
canvas で描くのも SVG.js で描くのも同じようなコードになりますが、SVG.js では SVG のコードが生成される点が大きく異なり、今回のコードの最後の部分は生成されたコードを取り出しているところです。生成されたコードは以下のとおりです。
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:svgjs="http://svgjs.dev/svgjs" width="300" height="300" style="background-color: cyan;">
<path d="M216 75, L84 225 A100 100, 0, 1, 1, 200 237" fill="none" stroke-width="50" stroke="#000000"/>
</svg>
“JavaScript (55) 「の」の字” への1件の返信