ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • canvas event
    노마드코더/javascript(바닐라JS 캔버스-초급) 2020. 5. 17. 12:27

     

     

    캔버스 위에 마우스가 있으면 그것을 감지하게 하는 방법.

    const canvas = document.getElementById("jsCanvas");
    
    let painting = false;
    
    function stopPainting(event) {
      painting = false;
    }
    
    function noMouseMove(event) {
      const x = event.offsetX;
      const y = event.offsetY;
      /*
       콘솔에 찍히는 좌표중, clientX,Y와 offsetX,Y가 있는데, 
       clientX,Y는 윈도우 화면에서의 좌표이고, 
       offsetX,Y는 캔버스 위에서의 좌표이다. 고로, 우리가 필요한 것은 offsetX,Y.
      */
    }
    
    function onMouseDown(event) {
      painting = true;
    }
    
    function onMouseUp(event) {
      stopPainting();
    }
    
    if (canvas) {
      canvas.addEventListener("mousemove", noMouseMove);
      //캔버스 위의 마우스 움직임을 감지함.
      canvas.addEventListener("mousedown", onMouseDown);
      //마우스를 클릭했을 때 
      canvas.addEventListener("mouseup", onMouseUp);
      //마우스 클릭을 떼었을 때
      canvas.addEventListener("mouseleave", stopPainting);
      //마우스가 캔버스를 떠났을 때  + stopPainting함수를 사용함으로써 재사용성을 높임. 
    }

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

    filling mode  (2) 2020.05.17
    Brush Size  (0) 2020.05.17
    recap!  (0) 2020.05.17
    2D context  (0) 2020.05.17

    댓글

Designed by Tistory.