Computer Science/웹 프로그래밍

캔버스와 JS(그림 그리기)

mitdog 2024. 7. 23. 21:49

도화지 태그가 html에서의 canvas.
그 도화지에 그림을 그리는게 js의 각종 메소드들.

Canvas

도화지 태그.

<canvas id="myCanvas"></canvas>
...
<script>
    ...
    context = document.getElementById('myCanvas')
    context.beginPath();
    ...
</script>

 

canvas와 JS를 연결하여 닷(dot;.)메소드로 그린다.

JS로 그리기

일단 무조건 context 객체로 받아서 사용한다.

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

 

그 다음에 사각형을 그리든, 배경을 넣든 하는 것이다.

 

색 꽉 채운 사각형 그리기

context.fillStyle = "#00FF00"; // fill 스타일 지정 후
context.fillRect(0, 0, 100, 50); // fill...(여기서는 fillRect) 사용

직선 그리기

context.beginPath(); // 새 선 시작
context.moveTo(0, 0); // 선 시작지점 (0,0)
context.lineTo(100, 100); // (100,100)까지 잇는 선 그리기
..
context.stroke(); // 만든 선을 실제로 그리기

beginPath를 안하면?

context.rect(10,10,100,100); // 사각형 1
context.fillStyle = "yellow";
context.fill(); // 노란색으로 채움

context.beginPath(); // 다음 그림, 만약 이게 없으면..
context.rect(110, 110, 50, 50); // 사각형 2
context.strokeStyle = "red"; // 선 색 빨강
context.stroke(); // 테두리 선 그리기

만약 beginPath()가 위 코드에서 없다면
사각형 1의 테두리 또한 빨간색으로 변한다.
즉, beginPath는 구분해주는 역할.


(출처: https://developer.mozilla.org/ko/docs/Web/API/Canvas_API/Tutorial/Drawing_shapes)

원 그리기

arc라는 메서드를 통해 그린다. 매개인자가 6개나 있는데 다음과 같다.
arc(x, y, r, sAngle, eAngle, counterclockwise)

  • x: 원 중심 x좌표
  • y: 원 중심 y좌표
  • r: 반지름
  • sAngle: 시작점 각도
  • eAngle: 끝점 각도
  • counterclockwise: 반시계 방향으로(얘는 선택적, 적지 않으면 시계방향으로 그림=기본값)

기본값: sAngle부터 eAnlgle까지 시계방향으로 그림
counterclockwise시: sAngle부터 eAngle까지 반시계 방향으로 그림

closePath()

그림의 시작 시작점과 끝점을 직선으로 잇는 그림을 그린다.

자유롭게 시작 점, 다음 점, 다음 점... , 마지막에 끝점과 시작 점 잇기. 로 삼각형을 그릴 수도 있다.

context.beginPath();
context.moveTo(50, 100);
context.lineTo(75, 50);
context.lineTo(100, 100);
context.closePath();
context.fillStyle = "green";
context.fill();

텍스트 그리기

context.font = 'italic 38pt Arial'; // same as CSS
context.fillText('Hello World!', 20, 100); // 문자열, 시작점x좌표, 시작점y좌표

.font로 스타일을 지정하고(CSS와 형식이 같다)
.fillText로 원하는 문구를 원하는 위치에 출력할 수 있다.