グラフを描く
例
y = sin x のグラフです。仕組みはソースを見てください。
canvasとは
canvas要素はHTML 5で描画するための新しい仕組みです。座標は左上隅が原点で,右が x,下が y の向きです。
canvasの使い方
このページの例は次のようにしています。
<head>
...(略)...
<script>
function draw() {
const canvas = document.getElementById('MyCanvas');
const context = canvas.getContext('2d');
context.strokeRect(1, 1, 628, 200);
context.beginPath();
context.moveTo(1, 101);
context.lineTo(629, 101);
context.stroke();
context.beginPath();
context.lineWidth=2;
context.moveTo(1, 101);
for (let i = 4; i <= 628; i += 4) {
context.lineTo(i + 1, 101 - 100 * Math.sin(0.01 * i));
}
context.stroke();
}
</script>
</head>
<body onload="draw()">
...(略)...
<canvas id="MyCanvas" width="630" height="202"></canvas>
...(略)...
</body>
描画の方法
draw() { ... } の中でcanvas要素のcontextを取得し,それに対して実際の描画を行います。
function draw() {
const canvas = document.getElementById('MyCanvas');
const context = canvas.getContext('2d');
// このcontextに対して描画する
}
例えば線分と円を描くには次のようにします。
context.beginPath(); // パスを開始 context.moveTo(20, 190); // ペンを紙に付けずに移動 context.lineTo(580, 10); // ペンを紙に付けて移動 context.stroke(); // パスに沿ってインクを流し込む(デフォルトでは1ピクセル幅) context.beginPath(); context.arc(300, 100, 90, 0, Math.PI * 2, true); // 円 context.strokeStyle = "#6699CC"; context.lineWidth=2; context.stroke();