canvas 및 2D 컨텍스트 설정하기
canvas 요소를 만들고 2D 렌더링 컨텍스트 가져오기
canvas 및 2D 컨텍스트 설정하기은(는) CoddyKit의 무료 HTML Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 HTML Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. HTML Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
canvas 요소
<canvas> 요소는 브라우저에서 그림을 그릴 수 있는 비트맵 표면입니다.
<canvas id="myCanvas" width="800" height="400">
<!-- Fallback for browsers without canvas support -->
<p>Your browser does not support HTML5 Canvas.</p>
</canvas>너비와 높이 속성
canvas 크기는 CSS가 아니라 HTML 속성으로 항상 설정하십시오.
<!-- CORRECT: set intrinsic size via attributes -->
<canvas width="800" height="400"></canvas>
<!-- WRONG: CSS changes display size but not canvas resolution -->
<canvas style="width: 800px; height: 400px;"></canvas>
<!-- This stretches a default 300x150 canvas to 800x400
Result: blurry graphics -->2D 컨텍스트 가져오기
그리기를 위해 2D 렌더링 컨텍스트를 가져옵니다.
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');
// ctx is a CanvasRenderingContext2D object
// All drawing operations are methods on ctx
// Check browser support:
if (!canvas.getContext) {
console.error('Canvas not supported');
}좌표계
canvas 좌표계는 왼쪽 위에서 시작합니다.
// (0, 0) = top-left corner
// (width, 0) = top-right
// (0, height) = bottom-left
// (width, height) = bottom-right
// For a 800x400 canvas:
// x increases left → right (0 to 800)
// y increases top → bottom (0 to 400)
//
// Example: draw at center:
ctx.fillRect(400, 200, 10, 10); // centered dotcanvas 상태
canvas에는 저장하고 복원할 수 있는 그리기 상태가 있습니다.
ctx.save(); // push current state onto a stack
// Change state:
ctx.fillStyle = 'red';
ctx.globalAlpha = 0.5;
// Draw with modified state...
ctx.fillRect(100, 100, 200, 200);
ctx.restore(); // pop state: back to pre-save settingscanvas 지우기
다시 그리기 전에 애니메이션을 위해 canvas 전체를 지웁니다.
// Clear entire canvas:
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Or with a background color:
ctx.fillStyle = 'white';
ctx.fillRect(0, 0, canvas.width, canvas.height);fillStyle과 strokeStyle
채우기와 선 그리기 작업에 사용할 색상을 설정합니다.
ctx.fillStyle = 'blue'; // CSS color name
ctx.fillStyle = '#ff6600'; // hex color
ctx.fillStyle = 'rgb(255, 100, 0)'; // rgb
ctx.fillStyle = 'rgba(255, 100, 0, 0.5)'; // rgba with alpha
ctx.fillStyle = gradient; // gradient object
ctx.fillStyle = pattern; // pattern object
ctx.strokeStyle = '#333333'; // border colorlineWidth 및 기타 스타일 속성
선과 선 그리기의 스타일 속성입니다.
ctx.lineWidth = 4; // stroke width in pixels
ctx.lineCap = 'round'; // butt | round | square
ctx.lineJoin = 'round'; // miter | round | bevel
ctx.setLineDash([5, 3]); // dashed line: 5px dash, 3px gap
ctx.globalAlpha = 0.8; // transparency for all drawing
ctx.globalCompositeOperation = 'multiply'; // blend modes반응형 HiDPI canvas
Retina/HiDPI 디스플레이에서 흐릿하게 보이는 canvas를 수정합니다.
function setupHiDPI(canvas, width, height) {
const dpr = window.devicePixelRatio || 1;
canvas.width = width * dpr;
canvas.height = height * dpr;
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
const ctx = canvas.getContext('2d');
ctx.scale(dpr, dpr); // scale all drawing
return ctx;
}Canvas와 SVG 비교
Canvas와 SVG 중 무엇을 선택할지 알아봅니다.
- Canvas — 비트맵 방식으로 픽셀 단위로 처리하며 게임, 대규모 데이터 시각화, 이미지 처리에 적합합니다
- SVG — 벡터 방식으로 크기를 조정할 수 있으며 로고, 아이콘, 상호 작용 요소가 있는 차트, 접근성에 적합합니다
Canvas 접근성
Canvas에는 기본 제공 접근성이 없으므로 직접 추가해야 합니다.
<canvas
id="chart"
width="800"
height="400"
aria-label="Bar chart showing Q1-Q4 revenue growth"
role="img"
>
<!-- Fallback for non-canvas browsers and screen readers -->
<table><!-- accessible data table --></table>
</canvas>빠른 확인
canvas 그리기 컨텍스트를 가져오는 올바른 방법은 무엇입니까?
복습: Canvas 설정
Canvas 설정의 핵심 내용입니다.
- 너비와 높이는 CSS가 아니라 HTML 속성으로 설정합니다
canvas.getContext('2d')— 그리기 컨텍스트를 가져옵니다- 왼쪽 위가 원점(0,0)이며 x→오른쪽, y→아래쪽입니다
ctx.save()/ctx.restore()— 스택 기반 상태 관리입니다- 선명한 Retina 렌더링을 위해 devicePixelRatio만큼 크기를 조정합니다
자주 묻는 질문
“canvas 및 2D 컨텍스트 설정하기” 강의는 무료인가요?
네 — “canvas 및 2D 컨텍스트 설정하기” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 HTML Academy 강의 전체를 잠금 해제할 수 있습니다. HTML Academy 강의에는 총 4개의 강의가 포함되어 있습니다.
“canvas 및 2D 컨텍스트 설정하기”에서 뭘 배우나요?
canvas 요소를 만들고 2D 렌더링 컨텍스트 가져오기 브라우저에서 직접 실행하는 실습 코드로 HTML Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
HTML Academy을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 HTML Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“canvas 및 2D 컨텍스트 설정하기” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 HTML Academy 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 HTML Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- canvas 및 2D 컨텍스트 설정하기
- 사각형과 경로 그리기
- canvas에 텍스트와 이미지 그리기
- requestAnimationFrame으로 애니메이션 만들기