HTML5 Canvas와 SVG는 웹에서 그래픽을 구현할 수 있는 기술이다.
1. HTML5 Canvas
1.1. 특징
- 픽셀 기반 그래픽: 캔버스에 그려진 이미지는 픽셀 단위로 렌더링.
- JavaScript 의존: 모든 그래픽은 JavaScript를 사용해 그려야 함.
- 애니메이션/실시간 업데이트: 게임, 데이터 시각화, 동적 애니메이션에 적합.
- 해상도 제한: 캔버스 크기를 늘리면 품질 저하 가능
1.2. 기본 사용
HTML
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #000;"></canvas>
JavaScript
- 2D 렌더링 컨텍스트 생성: getContext('2d') 사용.
- 도형, 텍스트, 이미지, 애니메이션 등을 그릴 수 있음.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// 사각형 그리기
ctx.fillStyle = 'blue';
ctx.fillRect(50, 50, 150, 100);
1.3. 주요 API
도형 그리기
- 사각형
- fillRect(x, y, width, height): 채워진 사각형.
- strokeRect(x, y, width, height): 테두리 사각형.
- clearRect(x, y, width, height): 영역 지우기.
- 원
ctx.beginPath();
ctx.arc(150, 75, 50, 0, Math.PI * 2); // x, y, 반지름, 시작각도, 끝각도
ctx.fill();
3. 경로
- beginPath(), moveTo(x, y), lineTo(x, y), stroke().
4. 이미지
const img = new Image();
img.src = 'image.jpg';
img.onload = () => {
ctx.drawImage(img, 0, 0, 300, 200); // (이미지, x, y, 너비, 높이)
};
5. 텍스트
ctx.font = '20px Arial';
ctx.fillStyle = 'red';
ctx.fillText('Hello Canvas', 50, 150);
2. SVG (Scalable Vector Graphics)
2.1. 특징
- 벡터 기반 그래픽: 확대/축소 시 품질 손실이 없음.
- XML 문법: HTML처럼 태그로 작성.
- DOM 통합: CSS, JavaScript로 조작 가능.
- 정적 이미지 및 간단한 그래픽에 적합
2.2. 기본 사용
HTML
<svg width="200" height="200">
<circle cx="100" cy="100" r="50" fill="blue" />
</svg>
결과
- 위 코드는 중심이 (100, 100)이고 반지름이 50인 파란색 원을 생성.
2.3. 주요 요소
- 도형
- <circle>: 원.
- <rect>: 사각형.
- <line>: 선.
- <polygon>: 다각형.
- <path>: 복잡한 경로.
<svg width="200" height="200">
<rect x="50" y="50" width="100" height="50" fill="green" />
<line x1="10" y1="10" x2="190" y2="190" stroke="red" stroke-width="2" />
</svg>
2. 텍스트
<svg width="300" height="100">
<text x="50" y="50" font-size="20" fill="black">Hello SVG</text>
</svg>
3. 그라디언트
<svg width="200" height="200">
<defs>
<linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
<stop offset="0%" style="stop-color:blue;stop-opacity:1" />
<stop offset="100%" style="stop-color:red;stop-opacity:1" />
</linearGradient>
</defs>
<rect width="200" height="200" fill="url(#grad1)" />
</svg>
2.4. CSS와 SVG
- CSS를 사용해 스타일링 가능.
<svg width="200" height="200">
<circle cx="100" cy="100" r="50" class="my-circle" />
</svg>
<style>
.my-circle {
fill: yellow;
stroke: black;
stroke-width: 2;
}
</style>
2.5. 애니메이션
- <animate> 태그: 속성 값 애니메이션.
<svg width="200" height="200">
<circle cx="100" cy="100" r="50" fill="blue">
<animate attributeName="r" from="50" to="10" dur="1s" repeatCount="indefinite" />
</circle>
</svg>
'HTML' 카테고리의 다른 글
시멘틱 코드 (1) | 2024.12.30 |
---|---|
HTML 테이블 (1) | 2024.12.30 |
링크와 미디어 삽입 (1) | 2024.12.27 |
요소 (1) | 2024.12.26 |
HTML 문서 구조 (2) | 2024.12.26 |