Canvas 基本描画 — const ctx = canvas.getContext('2d'); ctx.fillRect(0,0,100,100)
HTML5 の <canvas> は「絵を描くための領域」です。JavaScript から getContext('2d') を呼ぶと 描画用のペン(コンテキスト)が手に入り、四角形や線、文字などを描けます。初心者がまず試すのは「四角形を塗りつぶす」ことです。
基本のコード例
<canvas id="canvas" width="200" height="200" style="border:1px solid #ccc"></canvas>
<script>
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d"); // 2D描画コンテキストを取得
// 四角形を塗りつぶす (x=0, y=0, 幅=100, 高さ=100)
ctx.fillStyle = "red"; // 塗りつぶし色を指定
ctx.fillRect(0, 0, 100, 100);
</script>
HTMLfillStyle: 塗りつぶしの色。デフォルトは黒。fillRect(x, y, w, h): 四角形を描画。左上座標(x, y)と幅・高さを指定。
よく使うテンプレート集
複数の四角形を描く
ctx.fillStyle = "blue";
ctx.fillRect(20, 20, 50, 50);
ctx.fillStyle = "green";
ctx.fillRect(100, 50, 80, 40);
JavaScript枠線だけの四角形
ctx.strokeStyle = "black"; // 線の色
ctx.lineWidth = 3; // 線の太さ
ctx.strokeRect(50, 50, 100, 80);
JavaScript背景を塗りつぶす
ctx.fillStyle = "#f0f0f0";
ctx.fillRect(0, 0, canvas.width, canvas.height);
JavaScript円を描く
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2); // 中心(100,100)、半径50
ctx.fillStyle = "orange";
ctx.fill();
JavaScript文字を描く
ctx.font = "20px sans-serif";
ctx.fillStyle = "black";
ctx.fillText("Hello Canvas", 20, 180);
JavaScript例題: 簡単な旗を描く
<canvas id="flag" width="300" height="200" style="border:1px solid #ccc"></canvas>
<script>
const ctx = document.getElementById("flag").getContext("2d");
// 背景
ctx.fillStyle = "white";
ctx.fillRect(0, 0, 300, 200);
// 赤い四角
ctx.fillStyle = "red";
ctx.fillRect(50, 50, 200, 100);
// テキスト
ctx.fillStyle = "black";
ctx.font = "24px sans-serif";
ctx.fillText("My Flag", 100, 180);
</script>
HTML- 効果: 白背景に赤い長方形と文字を描画。Canvasの基本要素を組み合わせた例。
実務でのコツ
- 座標系: 左上が
(0,0)。右へ行くほど x が増え、下へ行くほど y が増える。 - 塗りと線を分ける:
fillStyleとstrokeStyleを使い分ける。 - パス操作: 複雑な図形は
beginPath()→moveTo()→lineTo()→fill()/stroke()。 - 再描画: Canvasは「絵を描いて終わり」。消したいときは
ctx.clearRect(0,0,w,h)で消してから再描画。 - アニメーション:
requestAnimationFrameを使って繰り返し描画すると動きが作れる。
ありがちなハマりポイントと対策
- 何も描かれない:
- 原因:
<canvas>にwidth/heightを指定していない。CSSだけでサイズを変えると内部解像度が変わらない。 - 対策: 属性でサイズを指定する。
- 原因:
- 色が変わらない:
- 原因:
fillStyleを設定していない。 - 対策:
ctx.fillStyle = "色";を必ず指定。
- 原因:
- 消せない:
- 対策:
ctx.clearRect(0,0,canvas.width,canvas.height)でクリア。
- 対策:
練習問題(簡単な絵を描いてみよう)
<canvas id="art" width="300" height="200" style="border:1px solid #ccc"></canvas>
<script>
const ctx = document.getElementById("art").getContext("2d");
// 背景
ctx.fillStyle = "skyblue";
ctx.fillRect(0, 0, 300, 200);
// 太陽
ctx.beginPath();
ctx.arc(250, 50, 30, 0, Math.PI * 2);
ctx.fillStyle = "yellow";
ctx.fill();
// 草
ctx.fillStyle = "green";
ctx.fillRect(0, 150, 300, 50);
// 家
ctx.fillStyle = "brown";
ctx.fillRect(80, 100, 80, 50);
ctx.fillStyle = "red";
ctx.beginPath();
ctx.moveTo(80, 100);
ctx.lineTo(120, 60);
ctx.lineTo(160, 100);
ctx.closePath();
ctx.fill();
</script>
HTML- 効果: 空・太陽・草・家を描いた簡単な風景。基本図形の組み合わせで絵が描ける。
直感的な指針
- Canvasは「絵を描く紙」、ctxは「ペン」。
- 四角形は
fillRect、円はarc、文字はfillText。 - 座標系を理解し、塗りと線を組み合わせると自由に描ける。
- まずは四角形を描いて色を変える → 円や文字へ応用 → 組み合わせて絵を作る。
