본문 바로가기
Javascript/GMA(2302~)

230607 자바스크립트 마우스를 따라다니는 유령 mousemove 이벤트, requestAnimationFrame( )

by hyerin1201 2023. 6. 7.

HTML

<body class="chapter-10">
  <div class="followAnimation">
    👻
  </div>
</body>

 

 

CSS

.followAnimation {
  position: fixed;
  top: 0;
  left: 0;
  will-change: transform;
  font-size: 5rem;
  border: 1px solid #ccc;

  transition: all 0.2s linear;
}

 

 

 

Javascript

// const ghost = document.querySelector(".followAnimation");
// document.addEventListener("mousemove", (e) => {
//   let mouseX = e.clientX;
//   let mouseY = e.clientY;

//   ghost.style.left = mouseX + "px";
//   ghost.style.top = mouseY + "px";
// })


const el = document.querySelector(".followAnimation");
let mouseX = 0;
let mouseY = 0;

let currentX = 0;
let currentY = 0;

document.body.addEventListener("mousemove", (e) => {
  mouseX = e.clientX;
  mouseY = e.clientY;
});

function tick() {
  currentX = mouseX;
  currentY = mouseY;

  el.style.transform = `translate(${currentX}px, ${currentY}px)`;
  requestAnimationFrame(tick);
};

tick();