💡 퀵 접속: htm.kr/canvas

HTML5 Canvas 태그 사용법

1. Canvas 태그란?

Canvas 태그는 웹 페이지에 그래픽을 그리는 데 사용됩니다. JavaScript를 통해 다양한 그래픽 요소를 그릴 수 있으며, 애니메이션, 게임, 데이터 시각화 등에 활용됩니다.

2. 기본 구조

Canvas 태그의 기본 사용법

<canvas id="myCanvas" width="300" height="200">
    브라우저가 Canvas를 지원하지 않습니다.
</canvas>

<script>
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    
    // 사각형 그리기
    ctx.fillStyle = 'red';
    ctx.fillRect(10, 10, 100, 100);
</script>

3. 자주 사용되는 속성

속성 설명 예시
width 캔버스 너비 <canvas width="300">
height 캔버스 높이 <canvas height="200">
id 캔버스 식별자 <canvas id="myCanvas">

4. 실제 사용 예제

<!-- 기본 도형 그리기 예제 -->
<div class="basic-example">
    <h3>기본 도형 그리기 예제</h3>
    <canvas id="basicCanvas" width="300" height="200">
        브라우저가 Canvas를 지원하지 않습니다.
    </canvas>
    <script>
        const canvas = document.getElementById('basicCanvas');
        const ctx = canvas.getContext('2d');
        
        // 사각형 그리기
        ctx.fillStyle = 'red';
        ctx.fillRect(10, 10, 100, 100);
        
        // 원 그리기
        ctx.beginPath();
        ctx.arc(200, 100, 50, 0, Math.PI * 2);
        ctx.fillStyle = 'blue';
        ctx.fill();
    </script>
</div>

<!-- 애니메이션 예제 -->
<div class="animation-example">
    <h3>애니메이션 예제</h3>
    <canvas id="animationCanvas" width="300" height="200">
        브라우저가 Canvas를 지원하지 않습니다.
    </canvas>
    <script>
        const canvas = document.getElementById('animationCanvas');
        const ctx = canvas.getContext('2d');
        
        let x = 0;
        function animate() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            ctx.fillStyle = 'green';
            ctx.fillRect(x, 50, 50, 50);
            x += 2;
            if (x > canvas.width) x = 0;
            requestAnimationFrame(animate);
        }
        animate();
    </script>
</div>

<!-- 이미지 그리기 예제 -->
<div class="image-example">
    <h3>이미지 그리기 예제</h3>
    <canvas id="imageCanvas" width="300" height="200">
        브라우저가 Canvas를 지원하지 않습니다.
    </canvas>
    <script>
        const canvas = document.getElementById('imageCanvas');
        const ctx = canvas.getContext('2d');
        
        const img = new Image();
        img.src = 'image.jpg';
        img.onload = function() {
            ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
        };
    </script>
</div>

<style>
    /* 기본 도형 예제 스타일 */
    .basic-example {
        margin: 20px 0;
        padding: 15px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }

    /* 애니메이션 예제 스타일 */
    .animation-example {
        margin: 20px 0;
        padding: 15px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }

    /* 이미지 예제 스타일 */
    .image-example {
        margin: 20px 0;
        padding: 15px;
        border: 1px solid #ddd;
        border-radius: 4px;
    }

    /* 반응형 스타일 */
    @media (max-width: 768px) {
        .basic-example,
        .animation-example,
        .image-example {
            margin: 10px 0;
            padding: 10px;
        }
    }
</style>

실제 브라우저에서 보여지는 모습:

기본 도형 그리기
애니메이션

💡 주의사항

  • canvas 태그는 JavaScript와 함께 사용됩니다.
  • getContext() 메서드를 사용하여 그리기 컨텍스트를 가져옵니다.
  • 캔버스 크기는 width와 height 속성으로 지정합니다.
  • 브라우저 호환성을 고려해야 합니다.

5. 스타일링 예제

<style>
    /* 기본 캔버스 스타일 */
    canvas {
        border: 1px solid #ddd;
        border-radius: 4px;
        background-color: #fff;
    }

    /* 반응형 스타일 */
    @media (max-width: 768px) {
        canvas {
            max-width: 100%;
            height: auto;
        }
    }
</style>

6. 성능 최적화 팁

  • 적절한 캔버스 크기를 설정합니다.
  • 불필요한 그리기 작업을 피합니다.
  • requestAnimationFrame을 사용하여 애니메이션을 최적화합니다.
  • 이미지와 텍스트를 캐싱합니다.

7. 검증 및 테스트

canvas 태그가 올바르게 사용되었는지 확인하는 방법:

  • W3C 마크업 검증 서비스 사용
  • 다양한 브라우저에서 테스트
  • 캔버스 렌더링 테스트
  • 성능 테스트
  • 접근성 검사 도구 사용