ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 2D context
    노마드코더/javascript(바닐라JS 캔버스-초급) 2020. 5. 17. 16:04

     

     

    canvas 태그는 

    html의 한 요소인데, 

    다른 점은 context를 갖는다는 것이다. 

     

    context라는 건 이 요소 안에서 우리가 픽셀에 접근할 수 있는 방법이다. 

     

    이론 적으로는 이 안에 있는 픽셀들인 것이다. 

     

    매우 쉽게 이 context를 만들 수 있는데, 

     

    아래와 같이 context variable을 만들면 된다.

     

    cosnt ctx = canvas.getContext('2d');

     

    2d뿐 아니라 많은 context가 있다. 3d.. 등등

     

    그리고 나면 내가 할 수 있는 context는 모두 갖게 된다.

     

    context로 라인도 그릴수 있고, 사각형, 색이 칠해진 사각형 등등 할 수 있다. 

     

    ** path는 line을 시작하는 것이다. 

     

    하지만 painting을 할때엔 path가 필요하진 않다. 

    painting을 하지 않을 때만 이걸 하길 원한다. 

     

    클릭하지 않고 떠다니는 건 path를 만들겠다는 것이다. 

    시작점에서부터 끝낼 때까지 라인을 만들기 위해 클릭하기를 기다리는 것이다. 

     

     

    path를 만드는 건 기본적으로 선(line), 선의 시작점을 만드는 것이다.

     

    시작점은 마우스가 움직이는 곳이라면 어디든지 되는 것이다.

    시작점부터 클릭한 곳까지 선을 만드는 것이다.

     

    ** 

    const canvas = document.getElementById("jsCanvas"),
      ctx = canvas.getContext("2d");
    
    ctx.strokeStyle = "#2c2c2c";
    //사용자가 첫번째 사용할때는 검정색으로 할 수 있도록 설정해놓음.
    ctx.lineWidth = 2.5;
    
    let painting = false;
    
    function stopPainting(event) {
      painting = false;
    }
    
    function startPainting() {
      painting = true;
    }
    
    function noMouseMove(event) {
      const x = event.offsetX;
      const y = event.offsetY;
      /*
       콘솔에 찍히는 좌표중, clientX,Y와 offsetX,Y가 있는데, 
       clientX,Y는 윈도우 화면에서의 좌표이고, 
       offsetX,Y는 캔버스 위에서의 좌표이다. 고로, 우리가 필요한 것은 offsetX,Y.
      */
      if (!painting) {
        ctx.beginPath();
        ctx.moveTo(x, y);
        /*캔버스 위에서 마우스가 움직이면서 path를 만드는 것이다. 
        마우스가 가는 곳으로 path를 옮기는 것.
        클릭하면 클릭한 위치가 그 path의 끝나는 지점으로서 선택된 것이다 
        */
      } else {
        ctx.lineTo(x, y);
        // lineTo()를 호출하면 이 점에서 여기로 연결되는 것이다.
        ctx.stroke();
      }
    }
    
    function onMouseDown(event) {
      painting = true;
    }
    
    if (canvas) {
      canvas.addEventListener("mousemove", noMouseMove);
      //캔버스 위의 마우스 움직임을 감지함.
      canvas.addEventListener("mousedown", startPainting);
      //마우스를 클릭했을 때
      canvas.addEventListener("mouseup", stopPainting);
      //마우스 클릭을 떼었을 때
      canvas.addEventListener("mouseleave", stopPainting);
      //마우스가 캔버스를 떠났을 때  + stopPainting함수를 사용함으로써 재사용성을 높임.
    }
    

     

     

     

     

     

     

    https://developer.mozilla.org/ko/docs/Web/API/CanvasRenderingContext2D

     

    CanvasRenderingContext2D

    The CanvasRenderingContext2D interface, part of the Canvas API, provides the 2D rendering context for the drawing surface of a canvas element. It is used for drawing shapes, text, images, and other objects.

    developer.mozilla.org

     

    '노마드코더 > javascript(바닐라JS 캔버스-초급)' 카테고리의 다른 글

    filling mode  (2) 2020.05.17
    Brush Size  (0) 2020.05.17
    recap!  (0) 2020.05.17
    canvas event  (0) 2020.05.17

    댓글

Designed by Tistory.