3D hover parallax effect

by Hugo Vale Pereira

HTML

<!-- 
Copiado de:
  [https://www.youtube.com/shorts/Aabh97P31FA]
  [https://vueuse.org/core/useParallax/]
-->


<div class="wrapper">
  <div class="perspective">
   
  </div>
</div>

CSS

body{
  height:300vh;
}

.wrapper {
  width: 300px;
  height: 400px;
 
  margin: auto; /* Center Horizontally*/
  perspective:300px; 
  
}

.perspective{
   width: 100%;
   height: 100%;
   
   background: red;
   transition: 0.3s ease-out;
   
}

JavaScript

let rect = document.querySelector(".wrapper").getBoundingClientRect()

// Isto devia ser feito novamente num evento de resizeWindow para que a posição da div seja atualizada. (ponto azul)
const { x, y } = {
  x: rect.x + rect.width / 2,
  y: rect.y + rect.height / 2,
}

const scaleFactor = 0.05

let center = document.createElement("div")
center.style.width = "5px"
center.style.height = "5px"
center.style.position = "absolute"
center.style.top = y + "px"
center.style.left = x + "px"
center.style.background = "blue"
document.body.appendChild(center)

window.addEventListener("mousemove", (e) => {
  document.querySelector(".perspective").style.transform =
    `rotateY(${(x - e.x) * scaleFactor}deg) rotateX(${-(y - e.y - window.scrollY) * scaleFactor}deg)`
})