빠른 참조

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, width, height
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) 및 원 그리기

// 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);

관련 주제