HTML & CSS
[HTML5 Canvas] #1 기본 사용법 (canvas태그, getContext(), fillStyle, fillRect)
권군이
2022. 7. 14. 18:37
- HTML
<canvas> 태그
<canvas id="canvas" width="150" height="150"></canvas>
Canvas API로 다양한 그래픽을 그리기 위해 <canvas> 태그를 이용한다.
<canvas> 태그는 width, height 속성을 가지고 있고, 기본값은 width=300px, height=150px로 지정된다.
-JavaScript
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
getContext()
canvas 요소는 getContext() 메서드를 이용해서, 랜더링 컨텍스트와 그리기 함수들을 사용할 수 있다.
getContext() 메서드는 렌더링 컨텍스트 타입을 지정하는 하나의 파라메터를 가진다.
2D 그래픽의 경우, 2d로 지정한다.
ctx.fillStyle = 'green';
ctx.fillRect(10,10,150,100);
fillStyle = color
: 도형을 채우는 색을 설정한다. (기본값은 검은색 #000000)
fillRect(x, y, width, height)
: 시작점이 (x,y)이고 너비와 높이가 width, height인 채워진 사각형을 그린다.
참고) https://developer.mozilla.org/ko/docs/Web/API/Canvas_API/Tutorial/Basic_usage