Canvasの基本的な使い方
HTML5のCanvas APIを使って、図形を描画する基本的な方法を学びます。Canvas要素は、JavaScriptを使って動的にグラフィックスを描画できる領域を提供します。
ファイルの用意
Section titled “ファイルの用意”次のように index.html、style.css、main.js の3つのファイルを作成してください。
./works└── canvas ├── index.html ├── style.css └── main.jsまず、HTMLファイルにCanvas要素を追加します。
index.html を作成する
Section titled “index.html を作成する”1<html>2 <head>3 <link rel="stylesheet" href="./style.css" />4 </head>5 <body>6 <canvas id="canvas" width="400" height="300"></canvas>7 <script src="./main.js"></script>8 </body>9</html>Canvas要素にはwidthとheight属性で描画領域のサイズを指定します。この例では400x300ピクセルのキャンバスを作成しています。
次に、スタイルシートでCanvasに枠線を追加します。
style.css を作成する
Section titled “style.css を作成する”1canvas {2 border: 1px solid #CCC;3}コンテキストの取得
Section titled “コンテキストの取得”Canvas上に描画を行うには、まず描画コンテキスト(2Dコンテキスト)を取得する必要があります。
const canvas = document.getElementById('canvas');const ctx = canvas.getContext('2d');getContext('2d')メソッドで2D描画用のコンテキストオブジェクトを取得します。このオブジェクトを通じて、さまざまな描画メソッドを呼び出すことができます。
四角形=矩形の描画
Section titled “四角形=矩形の描画”矩形(四角形)を描画するには、fillRect()メソッドを使用します。
// 四角形を描画ctx.fillStyle = 'lightblue';ctx.fillRect(50, 50, 150, 100);fillStyleで塗りつぶしの色を指定します(色名やHEXコード#ADD8E6が使えます)fillRect(x, y, width, height)で矩形を描画しますx, y: 左上の座標width, height: 幅と高さ
円を描画するには、パスを使用します。
// 円を描画ctx.beginPath();ctx.arc(300, 100, 50, 0, Math.PI * 2);ctx.fillStyle = 'lightcoral';ctx.fill();beginPath()で新しいパスを開始しますarc(x, y, radius, startAngle, endAngle)で円弧を定義しますx, y: 中心座標radius: 半径startAngle, endAngle: 開始角度と終了角度(ラジアン)
fill()でパスを塗りつぶします
arc の詳細については以下を参照してください。
https://developer.mozilla.org/ja/docs/Web/API/CanvasRenderingContext2D/arc
直線を描画するには、パスを使って始点と終点を指定します。
// 線を描画ctx.beginPath();ctx.moveTo(50, 200);ctx.lineTo(350, 200);ctx.strokeStyle = 'green';ctx.lineWidth = 5;ctx.stroke();moveTo(x, y)でパスの開始位置を設定しますlineTo(x, y)で指定座標まで線を引きますstrokeStyleで線の色を指定しますlineWidthで線の太さを指定しますstroke()でパスを描画します
複数の点をつないで線を描画
Section titled “複数の点をつないで線を描画”lineTo()を複数回使うことで、複数の点をつないだ線を描画できます。
// 線を描画ctx.beginPath();ctx.moveTo(50, 200);ctx.lineTo(350, 200);ctx.lineTo(200, 250);ctx.strokeStyle = 'green';ctx.lineWidth = 5;ctx.stroke();この例では、3つの点 (50, 200) → (350, 200) → (200, 250) をつないだ線が描画されます。lineTo()を追加するたびに、新しい点まで線が伸びていきます。
上記のコードをすべて組み合わせると、main.js は次のようになります。
main.js を作成する
Section titled “main.js を作成する”1const canvas = document.getElementById('canvas');2
3const ctx = canvas.getContext('2d');4
5// 四角形を描画6ctx.fillStyle = 'lightblue';7// ctx.fillStyle = '#ADD8E6';8ctx.fillRect(50, 50, 150, 100);9
10// 円を描画11ctx.beginPath();12ctx.arc(300, 100, 50, 0, Math.PI * 2);13ctx.fillStyle = 'lightcoral';14// ctx.fillStyle = '#F08080';15ctx.fill();16
17// 線を描画18ctx.beginPath();19ctx.moveTo(50, 200);20ctx.lineTo(350, 200);21ctx.lineTo(200, 250);22ctx.strokeStyle = 'green';23// ctx.strokeStyle = '#008000';24ctx.lineWidth = 5;25ctx.stroke();ブラウザで開くと、以下のような表示になります。

この章では、Canvas APIの基本的な使い方を学びました:
- Canvas要素をHTMLに配置し、
getContext('2d')で描画コンテキストを取得 fillRect()で矩形を描画arc()とfill()で円を描画moveTo()、lineTo()、stroke()で線を描画
これらの基本的な図形描画メソッドを組み合わせることで、より複雑な図形やグラフィックスを作成できます。