クイックリファレンス

HTML5 2D Canvas API チートシート

HTML5 2D Canvasの構文リファレンス:コンテキスト取得、基本図形、パス描画、座標変換、画像描画、状態の保存と復元(save/restore)。

· 公開日

HTML5 Canvas 2D レンダリングコンテキスト API (CanvasRenderingContext2D) のクイックリファレンス。

コンテキストの取得

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

基本図形の描画と塗りつぶし

// 線と塗りのスタイル指定
ctx.fillStyle = '#ff0000';
ctx.strokeStyle = '#0000ff';
ctx.lineWidth = 4;
ctx.lineCap = 'round'; // 'butt' | 'round' | 'square'

// 矩形描画メソッド:x, y, 幅, 高さ
ctx.fillRect(10, 20, 200, 100);
ctx.strokeRect(10, 20, 200, 100);
ctx.clearRect(0, 0, canvas.width, canvas.height);

パス(Path)と自由図形

ctx.beginPath();
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(100, 150);
ctx.closePath();

ctx.fill();
ctx.stroke();

円弧と真円の描画

// arc(x, y, radius, startAngle, endAngle, counterClockwise)
ctx.beginPath();
ctx.arc(100, 100, 50, 0, Math.PI * 2, false);
ctx.stroke();

描画状態スタック(Save & Restore)

ctx.save();    // 現在の描画状態をスタックに保存
// fillStyle や座標変換、クリッピング、影などを変更...
ctx.restore(); // スタックから直前の描画状態を復元

保存対象の状態一覧:strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation および現在の座標変換行列。


座標系変換 (Transforms)

ctx.translate(dx, dy);
ctx.rotate(angleInRadians);
ctx.scale(scaleX, scaleY);

// 任意の中心点 (ox, oy) を基準に回転
ctx.translate(ox, oy);
ctx.rotate(angle);
ctx.translate(-ox, -oy);

画像の描画と切り抜き

const img = new Image();
img.onload = () => {
  // 指定位置 (x, y) に原寸大で画像を描画
  ctx.drawImage(img, 0, 0);

  // リサイズ指定して描画: (img, dx, dy, dWidth, dHeight)
  ctx.drawImage(img, 0, 0, 150, 100);

  // 切り抜きと拡大縮小: (img, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)
  ctx.drawImage(img, 50, 50, 100, 100, 0, 0, 100, 100);
};
img.src = 'picture.jpg';

アニメーションループ実装パターン

function draw() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  // 各フレームの描画処理...
  requestAnimationFrame(draw);
}
requestAnimationFrame(draw);

関連テーマ