💡 퀵 접속: htm.kr/canvas
Canvas 태그는 웹 페이지에 그래픽을 그리는 데 사용됩니다. JavaScript를 통해 다양한 그래픽 요소를 그릴 수 있으며, 애니메이션, 게임, 데이터 시각화 등에 활용됩니다.
<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>
| 속성 | 설명 | 예시 |
|---|---|---|
| width | 캔버스 너비 | <canvas width="300"> |
| height | 캔버스 높이 | <canvas height="200"> |
| id | 캔버스 식별자 | <canvas id="myCanvas"> |
<!-- 기본 도형 그리기 예제 -->
<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>
<style>
/* 기본 캔버스 스타일 */
canvas {
border: 1px solid #ddd;
border-radius: 4px;
background-color: #fff;
}
/* 반응형 스타일 */
@media (max-width: 768px) {
canvas {
max-width: 100%;
height: auto;
}
}
</style>
canvas 태그가 올바르게 사용되었는지 확인하는 방법: