[ Java Script ] Canvas api

    Canvas api 

     = js로 그래픽 작업을 할 수 있도록 해주며 

       html 상에서 <canvas></canvas>를 입력한 후 js에서 이를 가져와 그래픽 작업을 할 수 있다.

     

    [ 시작 전에 해야할 일 ]

    canvas.getContext()를 통해 2d와 3d 상의 브러쉬를 가져오기

    canvas.width , canvas.height 설정하기

     

     

    오늘은 2d에 대해 적어볼까한다.

     

     

    [ 도형 그리기 ]

    특정 도형을 그리기 위해서는

    1. 그리고싶은 위치 잡기

    2. 선을 잇기

    3. 해당 도형은 단지 선으로만 연결할 지 선만으로 이루어지게 할지 결정하기

    크게 이 3단계를 거친다.

     

    [ 과정 ] 

     

    1단계

    canvas상의 좌표는 왼쪽 상단이 (0,0)이다.

    moveTo(x,y)라는 함수를 통해 시작 점을 찾는다.

     

    2단계

    lineTo(x,y)라는 함수를 통해 이동할 위치를 입력한다.

     

    3단계

    fill() 또는 stroke() 를 선택해 점을 연결하여 도형을 그린다.

    • fill() : 이어진 선들을 기준으로 안의 색이 채워지는 것
    • stroke() : 이어진 선들을 기준으로 안의 색이 채워지지않는 것

     

     

    예를 들어 삼각형을 그려보자

     

    canvas의 크기는 800x800으로 해주었다.

    삼각형은 세 개의 점이 있으니 출발지점 + 연결 지점 두 개가 필요하기에 moveTo() 1번 lineTo()을 2번 사용하였다.

    여기서 fill()를 입력했기에 핑크색 삼각형이 출력된다.

     

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Use Canvas api!</title>
      </head>
      <body>
        <canvas></canvas>
        <script>
          const canvas = document.querySelector("canvas");
          canvas.width = 800;
          canvas.height = 800;
          const ctx = canvas.getContext("2d");
          ctx.moveTo(325, 200);
          ctx.lineTo(200, 350);
          ctx.lineTo(450, 350);
          ctx.fillStyle = "pink";
          ctx.fill();
        </script>
      </body>
    </html>

     

    [ 주의점 ] 

    새로운 디자인의 도형을 그리는 경우에는 beginPath()를 사용해야한다.

     

    예를 들어 아래의 코드상으로는 초록색 도형과 분홍색 도형이 각각 한 개씩 그려져야하나

    beginPath()없는 경우 아래와 같은 결과가 나오게 된다.

     

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Use Canvas api!</title>
      </head>
      <body>
        <canvas></canvas>
        <script>
          const canvas = document.querySelector("canvas");
          canvas.width = 800;
          canvas.height = 800;
          const ctx = canvas.getContext("2d");
          ctx.moveTo(325, 200);
          ctx.lineTo(200, 350);
          ctx.lineTo(450, 350);
          ctx.fillStyle = "green";
          ctx.fill();
          ctx.moveTo(600, 200);
          ctx.lineTo(550, 350);
          ctx.lineTo(650, 350);
          ctx.fillStyle = "pink";
          ctx.fill();
        </script>
      </body>
    </html>

     

     

    그러나 아래의 코드처럼 첫번째 fill()이후에 beginPath()를 입력해준다면 원하던 초록색과 분홍색의 도형이 출력된다.

     

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Use Canvas api!</title>
      </head>
      <body>
        <canvas></canvas>
        <script>
          const canvas = document.querySelector("canvas");
          canvas.width = 800;
          canvas.height = 800;
          const ctx = canvas.getContext("2d");
          ctx.moveTo(325, 200);
          ctx.lineTo(200, 350);
          ctx.lineTo(450, 350);
          ctx.fillStyle = "green";
          ctx.fill();
          ctx.beginPath();
          ctx.moveTo(600, 200);
          ctx.lineTo(550, 350);
          ctx.lineTo(650, 350);
          ctx.fillStyle = "pink";
          ctx.fill();
        </script>
      </body>
    </html>


    [ 사각형과 원 그리기 ]

     

    [ 사각형 ]

    1. fillRect(x,y,width,height)
    2. strokeRect(x,y,width,height)

    [ 원 ]

    1. arc(x, y, radius, startang, lastang) + fill() or stroke()

    원의 경우 fill()과 stroke()를 따로 결정해주어야한다.

     

    또한 원은 startang과 lastang을 지정해줘야하는데 아래의 그림을 보면 이해하기 쉬울 것이다.

    시계를 기준으로 3시가 0의 값을 가지며 완전한 원을 그리고 싶을땐 arc(x, y, radius,0,2)라고 입력하면 되고

    arc(x, y, radius,0,1.5)라고 입력한 경우엔 오른쪽과 같은 도형이 생긴다.

     

     

     


    [ canvas와 관련된 함수 ]

     

    canvas에 이미지 띄우기

    document.querySelector("canvas").drawImage(이미지 경로명, x, y, width, height)

     

    fill로 도형을 그릴 경우 도형의 색상 변경하기

    document.querySelector("canvas").fillStyle ="color"

     

    stroke로 도형을 그릴 경우 도형의 색상 변경하기

    document.querySelector("canvas").strokeStyle = "color"

     

    style을 저장하는 함수 ( 색상, 브러쉬 모양 등)

    document.querySelector("canvas").save()

     

    저장한 style을 불러오는 함수

    document.querySelector("canvas").restore() 

     

    canvas에 string 넣기

    document.querySelector("canvas").fillText(string, x, y)

    document.querySelector("canvas").font = "font size , font Shape"를 통해 글씨체와 글씨 크기를 바꿀 수 있다.


    document.querySelector("canvas").lineCap = round, square, butt - 선의 끝 모양

    document.querySelector("canvas").lineWidth = ?? - 선의 굵기


    [ 만든 이미지 저장하기 ]

    html에 save 버튼을 두고 버튼을 누를 때마다 저장할 수 있도록 하는 코드이다.

    우리가 만든 이미지를 url로 변경하여 <a>에 삽입한 뒤 click을 발생시켜 다운받을 수 있다.

    const saveBtn = document.querySelector(".save-btn");
    saveBtn.addEventListener("click", saveImage);
    function saveImage() {
      var saveImageUrl = canvas.toDataURL();
      var a = document.createElement("a");
      a.href = saveImageUrl;
      a.download = "MyImage.jpg";
      a.click();
    }

     

     


    canvas api 공부하면서 만든 사이트

    https://dpqls0356.github.io/drawing-website/

    댓글