Programming language/Javasript

[Javascript] Canvas API - 간단한 기능구현(1)

pogles 2022. 12. 26. 21:50

프론트엔드에 역동적인 애니메이션이나 그림을 그리고 싶을 때 Javascrpipt 에서 canvas API 를 제공합니다.

 

앞서 HTML 에 <canvas></canvas> 만 먼저 추가해주시면 됩니다.이후에 동작들은 모두 Javascript 에서 진행합니다.

 

1. 다양한 모형 그리기

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d"); // 캔버스에 그림그릴때 context

canvas.width = 800; //css 뿐만 아니라 js에서도 표시
canvas.height = 800;

ctx.rect(50, 50, 100, 100); //canvas(50,50) 위치에서 width 100, height 100 인 사각형그리기
ctx.rect(150, 150, 100, 100);
ctx.rect(250, 250, 100, 100);
ctx.fill(); // 기본색(검정)으로 색채우기

ctx.beginPath(); // 새로운 ctx 경로 그리기
ctx.rect(350, 350, 100, 100);
ctx.fillStyle = "red"; //ctx 색상
ctx.fill();

 

 

See the Pen canvas by PogleJeong (@PogleJeong) on CodePen.


 

ctx.rect( x, y, width, height )ctx.moveTo 와 ctx.lineTo 기능을 간결하고 쉽게 사용할 수 있도록 도와줍니다.

 

ctx.rect() 로 사각형을 만드는데 1줄이지만 moveTo, lineTo 로 사각형을 만드는데는 5줄이 사용됩니다.

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d"); // 캔버스에 그림그릴때 context

canvas.width = 800; //css 뿐만 아니라 js에서도 표시
canvas.height = 800;

/* ctx.rect ( x, y, width, height )*/

ctx.rect(50,50,100,100);

/* ctx.moveTo (x,y) + ctx.lineTo(x,y) */

ctx.moveTo(50,50) // 마우스 50,50에 위치시키기
ctx.lineTo(150,50) // 마우스 위치(50,50)에서 (150,50)까지 선긋기
ctx.lineTo(150,150) // 마우스 위치(150,50)에서 (150,150)까지 선긋기
ctx.lineTo(50,150) // 마우스 위치(150,150)에서 (50,150)까지 선긋기
ctx.lineTo(50,50) // 마우스 위치(50,150)에서 (50,50)까지 선긋기

 


const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d"); // 캔버스에 그림그릴때 context

canvas.width = 800; //css 뿐만 아니라 js에서도 표시
canvas.height = 800;

ctx.fillRect(200, 200, 50, 200);
ctx.fillRect(400, 200, 50,  200);
ctx.lineWitdh = 2; // 선의 두께
ctx.strokeRect(300, 300, 50, 100); //문짝
ctx.moveTo(200, 200);
ctx.lineTo(325, 100);
ctx.lineTo(450, 200);
ctx.fill();

ctx.beginPath(); // 새로운 경로 설정
ctx.arc(250,100,50,0,2*Math.PI);
ctx.fill();

ctx.beginPath(); // 새로운 경로 설정
ctx.fillStyle = "red";
ctx.arc(240, 50, 5, 0 ,2*Math.PI);
ctx.fill();

 

 

See the Pen canvas house by PogleJeong (@PogleJeong) on CodePen.

 


  Method function
  fillRect(x,y,width,height)  색이 채워진 사각형 그리기
  strokeRect(x,y,width,height) 테두리만 있는 사각형 그리기
  clearRect(x,y,width,height) 특정 영역 지우기
  moveTo(x,y) canvas(x,y) 로 이동하기
  lineTo(x,y) 현재위치에서 canvas(x,y)까지 선그리기
  fill() / stroke() 색 채우기 / 테두리 그리기
  lineWidth = 5 선 두께 설정하기
  fillStyle = "색상" 채우기 색상 정하기
  arc(x,y,반지름,
시작각도, 종료각도, 그리는방향)
원그리기 (그리는방향 true = 좌방향, false = 우방향)
  beginPath() 새로운 경로 설정(이전 경로와의 선이 생성 방지)