Created
June 1, 2024 05:17
-
-
Save rahulspace/c936425045ef078f9c60ad3813e18e39 to your computer and use it in GitHub Desktop.
Tilt React Component Move Using Framer Motion - Tilt Children On Mouse
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// components/Tilt.js | |
import React, { useState, useEffect } from "react"; | |
import { motion } from "framer-motion"; | |
const Tilt = ({ children }) => { | |
const [mousePosition, setMousePosition] = useState({ x: window.innerWidth / 2, y: window.innerHeight / 2 }); | |
useEffect(() => { | |
const handleMouseMove = (e) => { | |
setMousePosition({ | |
x: e.clientX, | |
y: e.clientY, | |
}); | |
}; | |
window.addEventListener('mousemove', handleMouseMove); | |
return () => { | |
window.removeEventListener('mousemove', handleMouseMove); | |
}; | |
}, []); | |
const calculateTilt = (x, y) => { | |
const middleX = window.innerWidth / 2; | |
const middleY = window.innerHeight / 2; | |
const offsetX = (x - middleX) / middleX; | |
const offsetY = (y - middleY) / middleY; | |
const rotationX = offsetY * 20; // Adjust the multiplier to control the tilt angle | |
const rotationY = offsetX * -20; // Adjust the multiplier to control the tilt angle | |
return { rotateX: rotationX, rotateY: rotationY }; | |
}; | |
const tilt = calculateTilt(mousePosition.x, mousePosition.y); | |
return ( | |
<motion.div | |
style={{ | |
transform: `rotateX(${tilt.rotateX}deg) rotateY(${tilt.rotateY}deg) translateZ(75px)`, | |
transformStyle: "preserve-3d", | |
}} | |
transition={{ type: "spring", stiffness: 300, damping: 20 }} | |
> | |
{children} | |
</motion.div> | |
); | |
}; | |
export default Tilt; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment