본문 바로가기

카테고리 없음

마우스 움직임 추적하기

반응형
<body>
  <h1>x : <span id="x"></span>, y : <span id="y"></span></h1>

  <script>
    window.addEventListener("mousemove", 마우스추적);
    var x = document.querySelector("#x");
    var y = document.querySelector("#y");
   

    function 마우스추적 (event){

      var x = document.querySelector("#x");
      var y = document.querySelector("#y");
      x. innerHTML = event.clientX;
      y. innerHTML = event.clientY;
      console.log (event);
    }
  </script>

</body>

window에다가 이벤트를 달아주었고 x y에 inner html 값으로 브라우저에 랜더링 된 client x y 축 좌표를 할당했기 때문에 가능

<body>
  <h1>x : <span id="x"></span>, y : <span id="y"></span></h1>
  <div id="cursor"></div>

  <script>
    window.addEventListener("mousemove", 마우스추적);
    var x = document.querySelector("#x");
    var y = document.querySelector("#y");
    var cursor = document.querySelector("#cursor");

   

    function 마우스추적 (event){

      var x = document.querySelector("#x");
      var y = document.querySelector("#y");
      x. innerHTML = event.clientX;
      y. innerHTML = event.clientY;

      cursor.style.top = event.clientY + "px";
      cursor.style.left = event.clientX + "px";
    }
  </script>

</body>
body {
  cursor: none;
}

#cursor {
  position: absolute;
  top: 0;
  left: 0;

  width: 50px;
  height: 50px;
  background-color: yellow;
}

마우스 커서 왼쪽 위에위치

      cursor.style.top = (event.clientY-25) + "px";
      cursor.style.left = (event.clientX-25) + "px";

 

커서를 가운데에 하기 위해서 css #cursor 에 width,height 값 (50px) 에서 반인 25px를 뺌

 

  #cursor {
    position: absolute;
    top: 0;
    left: 0;

    width: 50px;
    height: 50px;
    background-color: yellow;

    border-radius: 50%;

 

cursor에 border-radius 50%를 주면 동그란 모양으로 변경 가능 


translate로 표현하기 

      cursor.style.top = event.clientY + "px";
      cursor.style.left = event.clientX + "px";

 

      cursor.style.transform = "translate("+event.clientX +"px," + event.clientY+"px)"
      var x = document.querySelector("#x");
      var y = document.querySelector("#y");
      x. innerHTML = event.clientX;
      y. innerHTML = event.clientY;
      let value = +(event.clientX -25) +"px," + (event.clientY-25) +"px";

      cursor.style.transform = "translate(" + value + ")";
    }

 


<body>
  <div id="targetbox">
    <div id="blind"></div>
    <h1>안녕하세요 김다영입니다.</h1>
  </div>

  <script>
    var targetbox = document.querySelector("#targetbox");
    var blind = document.querySelector("#blind");

    targetbox.addEventListener("mousemove", function(e){
      blind.style.transform = "translateX(" + e.clientX + "px)";

    })
  </script>


</body>
#targetbox{
  width: auto;
  display: inline-block;
  position: relative;
  overflow: hidden;
}

#targetbox h1{
  margin: 0px;
  padding: 20px;
  font-size: 1.5rem;

}

#blind {
  width: 100%;
  height: 100%;
  position: absolute;
  background-color: white;

  top: 0;
  left: 0;
}

안녕하세요 김다영입니다 를 마우스 움직임에 따라 생성

 

반응형