[js]canvas 기초

eunalee·2023년 4월 17일
0

vanilla

목록 보기
1/2

js이용해서 화면에 그림그리기!

✨ Setting

html, css는 그저 거들뿐

  <body>
      <canvas></canvas>
      <script src="app.js"></script>
  </body>

javascript에서 canvas element 불러와 + 브러쉬 설정(context) + 화면크기지정

  const canvas = document.querySelector("canvas");
  const ctx = canvas.getContext("2d");

  //cavas 크기를 지정해줘야해. 이 네모의 왼/위가 (0,0)
  canvas.width = 800;
  canvas.height = 800;

✨ Drawing a rectangle

네모그리기

	ctx.fillRect(50, 50, 100, 200);

x위치, y위치, width, height
이 경우, default로 검정색 갖는다

stroke 네모

	ctx.strokeRect(50, 50, 100, 200);

색깔 네모

	ctx.rect(250,250,100,100);
    ctx.fillStyle = "red"
    ctx.fill();

알록달록 네모

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

  ctx.beginPath(); 
  ctx.rect(250,250,100,100);
  ctx.fillStyle = "red"
  ctx.fill();

위는 검정으로 그려지고 beginPath으로 한번 끊고 다시 시작해서 빨강
저거로 끊지 않아주면 그냥 몽땅 빨강박스된다.

참고

해체 네모

  ctx.moveTo(50, 50);
  ctx.lineTo(100, 50);
  ctx.lineTo(100, 100);
  ctx.lineTo(50, 100);
  ctx.lineTo(50, 50);
  ctx.brush();

moveTo로 시작점을 잡고 => 이동 이동 이동 ...
brush로 마무리하면 테두리네모, fill로 마무리하면 꽉찬 네모가 된다.

이때, 이동 이동의 순서가 중요하다. lineTo로 이동된 포인트에서 다시 시작해서 그린다고 생각해야지, 아무렇게나 점만 찍어대면 이상한 모양이 나온다.

  ctx.moveTo(50, 50);
  ctx.lineTo(50, 100);
  ctx.lineTo(100, 50);
  ctx.lineTo(100, 100);
  ctx.lineTo(50, 50);
  ctx.fill();
리본이 되어버렸다.

✨ Drawing a circle

  ctx.arc(250, 100, 50, 0, 2*Math.PI)
  ctx.fill();

x위치, y위치, 동그라미크기, 0(시작점), 끝나는 점

0, Math.PI => 밥공기 모양
Math.PI, 2*Math.PI => 거꾸로 밥공기 모양
0, 1.5Math.PI => 누가 1/4피자 먹고 남은모양

profile
coucou!

0개의 댓글