Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save JamesGelok/d033772a853bd326677ebbca0d193e3f to your computer and use it in GitHub Desktop.
Save JamesGelok/d033772a853bd326677ebbca0d193e3f to your computer and use it in GitHub Desktop.
import React, { useEffect } from 'react';
import { useSpring, animated } from 'react-spring';
const trans = (x, y, s) => `perspective(600px) rotateX(${x}deg) rotateY(${y}deg) scale(${s})`;
export default function Floater({ children }) {
const ref = React.createRef();
let height = 1;
let width = 1;
let xOffset = 1;
let yOffset = 1;
useEffect(() => {
const { x, y, width: w, height: h } = ref.current.getBoundingClientRect();
width = w;
height = h;
xOffset = x;
yOffset = y;
}, [ref]);
const calc = (x, y) => [
-(y - yOffset - height / 2) / 50,
(x - xOffset - width / 2) / 50,
1.04,
];
const [springProps, set] = useSpring(() => ({
xys: [0, 0, 1],
config: { mass: 5, tension: 350, friction: 40 },
}));
return (
<animated.div
ref={ref}
onMouseMove={({ clientX: x, clientY: y }) => set({ xys: calc(x, y) })}
onMouseLeave={() => set({ xys: [0, 0, 1] })}
onMouseDown={() => set({ xys: [0, 0, 1] })}
style={{ transform: springProps.xys.interpolate(trans) }}
>
{children}
</animated.div>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment