부드럽게 따라다니는 마우스

beomhak lee·2024년 4월 20일

work_tip

목록 보기
17/37
post-thumbnail
<div class="react-mon"></div>
 .react-mon {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      width: 50px;
      height: 50px;
      margin: auto;
      background-color: red;
    }
 (() => {
    const reactMonElem = document.querySelector('.react-mon');
    const targetPos = { x: 0, y: 0 };
    const easeValue = 0.05;
    const reactMonInfo = {
      x: 0,
      y: 0
    };
    
    window.addEventListener('mousemove', (e) => {
      targetPos.x = e.clientX - innerWidth * 0.5;
      targetPos.y = e.clientY - innerHeight * 0.5;
    });

    let dx;
    let dy;
    function render() {
      dx = targetPos.x - reactMonInfo.x;
      dy = targetPos.y - reactMonInfo.y;
      reactMonInfo.x = reactMonInfo.x + dx * easeValue;
      reactMonInfo.y = reactMonInfo.y + dy * easeValue;
      reactMonElem.style.transform = `translate3d(${reactMonInfo.x}px, ${reactMonInfo.y}px, 0px)`;
      requestAnimationFrame(render);
    }

    render();
  })();

0개의 댓글