HTML, CSS

HTML5 Canvas ✅ 도형 그리기와 실무 활용 예시

jonbeo 2025. 10. 31. 10:02
반응형

 

<canvas>는 HTML5에서 추가된 태그로, 픽셀 단위의 그래픽 처리를 지원합니다.
자바스크립트와 함께 사용해야만 그림을 그릴 수 있습니다.

 
<canvas id="myCanvas" width="400" height="400"></canvas>
 
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d"); // 2D 컨텍스트

⬛ 1. 사각형 그리기

 
// 채워진 사각형
ctx.fillStyle = "blue";
ctx.fillRect(50, 50, 100, 100);

// 테두리 사각형
ctx.strokeStyle = "red";
ctx.strokeRect(200, 50, 100, 100);

// 사각형 지우기
ctx.clearRect(80, 80, 40, 40);

⚪ 2. 원(원형) 그리기

 
ctx.beginPath();
ctx.arc(150, 250, 50, 0, Math.PI * 2); // (x, y, 반지름, 시작각, 끝각)
ctx.fillStyle = "green";
ctx.fill();

📏 3. 선(Line) 그리기

 
ctx.beginPath();
ctx.moveTo(50, 350);   // 시작 좌표
ctx.lineTo(350, 350);  // 끝 좌표
ctx.strokeStyle = "black";
ctx.lineWidth = 3;
ctx.stroke();

🖊️ 4. 텍스트 그리기

 
ctx.font = "24px Arial";
ctx.fillStyle = "purple";
ctx.fillText("Hello Canvas!", 100, 50);

ctx.strokeStyle = "orange";
ctx.strokeText("Outline Text", 100, 100);

🎞️ 5. 애니메이션 (requestAnimationFrame 활용)

 
let x = 0;
function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.arc(x, 200, 30, 0, Math.PI * 2);
  ctx.fillStyle = "blue";
  ctx.fill();

  x += 2;
  requestAnimationFrame(animate); // 반복 호출
}
animate();

 

👉 기본 애니메이션 원리 = 지우기 → 다시 그리기 → requestAnimationFrame 반복


📊 6. 실무 활용 예시

  • ✅ 데이터 시각화 (차트, 그래프)
  • ✅ 게임 개발 (2D 게임, 충돌 감지)
  • ✅ 시뮬레이션 (물리 엔진, 애니메이션 효과)
  • ✅ 이미지 필터, 비디오 렌더링

📝 마무리 정리

  • <canvas>는 픽셀 단위 그래픽 처리 → 강력하지만 DOM 요소처럼 접근 불가
  • 도형, 텍스트, 애니메이션 기본기만 알아도 활용 범위 넓음
  • 실무에서는 Chart.js, Three.js, Pixi.js 같은 라이브러리와 함께 자주 사용
반응형