JS에서 canvas를 사용해 브라우저에 2D 혹은 3D 그래픽을 그릴 수 있음.
const canvas = document.querySelector("canvas");
캔버스에 그림을 그릴 때 사용하는 붓 = context
const context = canvas.getContext("2d");
css에서 캔버스 크기 설정을 한 후 js에서도 작성해준다.
canvas {
width:800px;
height:800px;
border:5px solid black;
}
canvas.width = 800;
canvas.height = 800;
이후에는 width 와 height를 js에서만 수정할 것임 (css에서 X)
캔버스 왼쪽 코너 맨위가 기준 (0, 0)
사각형 채우는 함수 = fillRect (단축함수)
ctx.fillRect(x좌표, y좌표, 가로길이, 세로길이);
1. ctx.rect(50, 50, 100, 200); //선을 만듦(색 적용x)
2-1. ctx.stroke() //선이 그려짐
2-2. ctx.fill() //색이 채워짐
이 모든 과정을 합쳐놓은 함수가 fillRect
ctx.rect(50, 50, 100, 100);
ctx.rect(150, 150, 100, 100);
ctx.rect(250, 125, 100, 100);
ctx.fillStyle = "red";
ctx.fill();
하지만 이렇게 하면 같은 경로를 이어가기 때문에 앞에 그려놓은 사각형들도 빨강색으로 채워진다. 따라서 원래 경로를 끊고 새 경로로 시작해야 한다.
ctx.rect(50, 50, 100, 100);
ctx.rect(150, 150, 100, 100);
ctx.rect(250, 125, 100, 100);
ctx.fill();
ctx.beginPath(); //새 경로를 만들어줌
ctx.rect(350, 350, 100, 100);
ctx.fillStyle = "red";
ctx.fill();
fillRect = fill + Rect = fill + (moveTo + lineTo)
ex)
ctx.moveTo(50, 50);
ctx.lineTo(150, 50);
ctx.lineTo(150, 150);
ctx.lineTo(50, 150);
ctx.lineTo(50, 50);
ctx.fill();
원 그려주는 함수
ctx.arc(x좌표, y좌표, 반지름, starting angle, ending angle);
ex)
ctx.arc(290, 150, 50, 0, 2 * Math.PI);
ctx.fill();
ctx.beginPath();
ctx.fillStyle = "red";
ctx.arc(265, 140, 5, 0, 2 * Math.PI);
ctx.arc(315, 140, 5, 0, 2 * Math.PI);
ctx.fill();