JavaScript Canvas 통합 실습

학습 목표

각 예제는 독립적으로 실행되는 코드다. 브라우저에서 이 HTML 파일을 열어 결과를 확인한다.

1. Canvas 기본 구조

<canvas>는 그림을 표시할 영역이며, getContext("2d")는 2차원 그리기 도구를 가져온다.

<canvas id="myCanvas" width="600" height="400"></canvas>

<script>
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
</script>

위 캔버스는 가로 600픽셀, 세로 160픽셀의 빈 그림 영역이다.

2. 사각형 그리기

fillRect(x, y, width, height)는 내부가 채워진 사각형을, strokeRect()는 테두리 사각형을 그린다.

ctx.fillStyle = "skyblue";
ctx.fillRect(40, 35, 180, 110);

ctx.strokeStyle = "red";
ctx.lineWidth = 4;
ctx.strokeRect(270, 35, 180, 110);

3. 선 그리기

beginPath()로 경로를 시작하고 moveTo(), lineTo()로 점을 연결한 뒤 stroke()로 선을 표시한다.

ctx.beginPath();
ctx.moveTo(50, 140);
ctx.lineTo(180, 35);
ctx.lineTo(310, 140);
ctx.strokeStyle = "blue";
ctx.lineWidth = 5;
ctx.stroke();

4. 원 그리기

arc(x, y, radius, startAngle, endAngle)를 사용한다. 원 전체를 그릴 때 종료 각도는 Math.PI * 2다.

ctx.beginPath();
ctx.arc(180, 95, 60, 0, Math.PI * 2);
ctx.fillStyle = "orange";
ctx.fill();
ctx.strokeStyle = "#333";
ctx.stroke();

5. 삼각형 그리기

세 꼭짓점을 moveTo()와 lineTo()로 연결하고 closePath()로 경로를 닫는다.

ctx.beginPath();
ctx.moveTo(180, 25);
ctx.lineTo(90, 155);
ctx.lineTo(270, 155);
ctx.closePath();
ctx.fillStyle = "gold";
ctx.fill();
ctx.stroke();

6. 색상과 그라데이션

createLinearGradient()로 색상이 점진적으로 변하는 그라데이션을 만든다.

const gradient = ctx.createLinearGradient(40, 0, 500, 0);
gradient.addColorStop(0, "red");
gradient.addColorStop(0.5, "yellow");
gradient.addColorStop(1, "blue");

ctx.fillStyle = gradient;
ctx.fillRect(40, 40, 500, 100);

7. 텍스트 출력

font로 글꼴을 지정하고 fillText()로 글자를 출력한다. strokeText()는 글자 테두리를 그린다.

ctx.font = "bold 32px Arial";
ctx.fillStyle = "navy";
ctx.fillText("Hello Canvas!", 45, 75);

ctx.font = "bold 28px Arial";
ctx.strokeStyle = "tomato";
ctx.strokeText("JavaScript", 45, 135);

8. 좌표 이동과 회전

save()는 현재 그리기 상태를 저장하고 restore()는 복원한다. translate()로 회전 중심을 옮긴 다음 rotate()를 적용한다.

ctx.save();
ctx.translate(300, 110);
ctx.rotate(Math.PI / 4); // 45도
ctx.fillStyle = "purple";
ctx.fillRect(-50, -50, 100, 100);
ctx.restore();

주의: Canvas의 rotate()는 도(degree)가 아니라 라디안(radian)을 사용한다. 45도는 Math.PI / 4다.

9. 애니메이션: 움직이고 회전하는 사각형

마지막 실습은 사각형이 좌우로 이동하면서 회전하는 애니메이션이다. 매 프레임마다 이전 화면을 지우고 새로운 위치에 다시 그린다.

let x = 60;
let angle = 0;
let direction = 1;
let animationId = null;

function animate() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.save();
    ctx.translate(x, 130);
    ctx.rotate(angle);
    ctx.fillStyle = "deepskyblue";
    ctx.fillRect(-30, -30, 60, 60);
    ctx.restore();

    x += 2 * direction;
    angle += 0.04;

    if (x > 550 || x < 50) {
        direction *= -1;
    }

    animationId = requestAnimationFrame(animate);
}

시작 버튼을 누르면 애니메이션이 실행된다. 일시 정지 후 시작 버튼을 누르면 현재 위치에서 다시 진행한다.

10. 핵심 문법 요약

분류문법기능
초기화getContext("2d")2D 그리기 환경 생성
사각형fillRect(), strokeRect()채운 사각형, 테두리 사각형
경로beginPath(), closePath()경로 시작과 닫기
선moveTo(), lineTo(), stroke()선 연결과 표시
원arc()원호와 원 그리기
색상fillStyle, strokeStyle채우기와 선 색상
텍스트fillText(), strokeText()글자 출력
변환translate(), rotate(), scale()이동, 회전, 크기 변경
상태save(), restore()그리기 상태 저장과 복원
애니메이션requestAnimationFrame()다음 화면 프레임 예약
확장 과제
  1. 사각형의 색상을 무작위로 바꿔 본다.
  2. 원과 삼각형에도 회전 애니메이션을 적용한다.
  3. 반복문으로 여러 개의 사각형을 배치한다.
  4. 재귀 함수를 이용해 사각형 프랙탈을 구현한다.

11. 예제 통합 HTML 구조

아래는 앞에서 살펴본 기본 구조, 사각형, 선, 원, 삼각형, 그라데이션, 텍스트, 좌표 변환, 애니메이션을 하나의 HTML 문서 안에 정리한 통합 예제입니다. 원본의 각 예제와 설명은 그대로 두고, 참고용 통합 코드를 하단에 추가했습니다.

<!DOCTYPE html>
<html lang="ko">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Canvas 예제 통합 구조</title>
</head>
<body>
  <main>
    <h1>Canvas 예제 통합 실습</h1>
    <section><h2>기본 구조와 도형 예제</h2>
      <canvas id="shapeCanvas" width="600" height="420"></canvas>
    </section>
    <section><h2>애니메이션 예제</h2>
      <canvas id="animationCanvas" width="600" height="180"></canvas>
      <button id="startBtn" type="button">시작</button>
      <button id="pauseBtn" type="button">일시 정지</button>
      <button id="resetBtn" type="button">초기화</button>
    </section>
  </main>
  <script>
    // 하나의 Canvas에 사각형, 선, 원, 삼각형, 그라데이션, 텍스트, 회전을 통합합니다.
    const canvas = document.getElementById("shapeCanvas");
    const ctx = canvas.getContext("2d");

    // 사각형
    ctx.fillStyle = "skyblue";
    ctx.fillRect(30, 30, 120, 70);
    ctx.strokeStyle = "red";
    ctx.lineWidth = 4;
    ctx.strokeRect(175, 30, 120, 70);

    // 선
    ctx.beginPath();
    ctx.moveTo(330, 100);
    ctx.lineTo(390, 25);
    ctx.lineTo(450, 100);
    ctx.strokeStyle = "blue";
    ctx.lineWidth = 5;
    ctx.stroke();

    // 원
    ctx.beginPath();
    ctx.arc(95, 195, 45, 0, Math.PI * 2);
    ctx.fillStyle = "orange";
    ctx.fill();
    ctx.strokeStyle = "#333";
    ctx.stroke();

    // 삼각형
    ctx.beginPath();
    ctx.moveTo(245, 145);
    ctx.lineTo(195, 235);
    ctx.lineTo(295, 235);
    ctx.closePath();
    ctx.fillStyle = "gold";
    ctx.fill();
    ctx.stroke();

    // 그라데이션
    const gradient = ctx.createLinearGradient(340, 0, 560, 0);
    gradient.addColorStop(0, "red");
    gradient.addColorStop(0.5, "yellow");
    gradient.addColorStop(1, "blue");
    ctx.fillStyle = gradient;
    ctx.fillRect(330, 155, 230, 55);

    // 텍스트
    ctx.font = "bold 25px Arial";
    ctx.fillStyle = "navy";
    ctx.fillText("Hello Canvas!", 30, 300);
    ctx.font = "bold 23px Arial";
    ctx.strokeStyle = "tomato";
    ctx.strokeText("JavaScript", 30, 345);

    // 좌표 이동 및 회전
    ctx.save();
    ctx.translate(420, 300);
    ctx.rotate(Math.PI / 4); // 45도는 Math.PI / 4 라디안
    ctx.fillStyle = "purple";
    ctx.fillRect(-35, -35, 70, 70);
    ctx.restore();

    // requestAnimationFrame을 사용하는 이동·회전 애니메이션
    const movingCanvas = document.getElementById("animationCanvas");
    const movingCtx = movingCanvas.getContext("2d");
    let x = 60, angle = 0, direction = 1, animationId = null;

    function animate() {
      movingCtx.clearRect(0, 0, movingCanvas.width, movingCanvas.height);
      movingCtx.save();
      movingCtx.translate(x, 90);
      movingCtx.rotate(angle);
      movingCtx.fillStyle = "deepskyblue";
      movingCtx.fillRect(-30, -30, 60, 60);
      movingCtx.restore();
      x += 2 * direction;
      angle += 0.04;
      if (x > movingCanvas.width - 50 || x < 50) direction *= -1;
      animationId = requestAnimationFrame(animate);
    }

    document.getElementById("startBtn").addEventListener("click", () => {
      if (animationId === null) animationId = requestAnimationFrame(animate);
    });
    document.getElementById("pauseBtn").addEventListener("click", () => {
      if (animationId !== null) cancelAnimationFrame(animationId);
      animationId = null;
    });
    document.getElementById("resetBtn").addEventListener("click", () => {
      if (animationId !== null) cancelAnimationFrame(animationId);
      animationId = null;
      x = 60;
      angle = 0;
      direction = 1;
      movingCtx.clearRect(0, 0, movingCanvas.width, movingCanvas.height);
    });
  </script>
</body>
</html>