Javascript/GMA(2302~)

230607 ์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ ๋งˆ์šฐ์Šค๋ฅผ ๋”ฐ๋ผ๋‹ค๋‹ˆ๋Š” ์œ ๋ น mousemove ์ด๋ฒคํŠธ, requestAnimationFrame( )

hyerin1201 2023. 6. 7. 17:02

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();