Last active
August 16, 2022 20:12
-
-
Save crevulus/618b083983b855bec83c4730b117e0e2 to your computer and use it in GitHub Desktop.
A react-three-fiber cube that rotates idly, and spins back to position on hover using react-spring.
This file contains 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
import { Canvas } from "@react-three/fiber"; | |
import { Box } from "./components/Box"; | |
import "./styles.css"; | |
import React from "react"; | |
export const LightSource = () => { | |
return ( | |
<> | |
<ambientLight intensity={0.1} /> | |
<directionalLight position={[0, 0, 5]} /> | |
</> | |
); | |
}; | |
const App = () => { | |
return ( | |
<div | |
style={{ | |
height: "100vh", | |
width: "100vw" | |
}} | |
> | |
<Canvas> | |
<LightSource /> | |
<Box /> | |
</Canvas> | |
</div> | |
); | |
}; | |
export default App; |
This file contains 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
import React, { useState, useRef } from "react"; | |
import { Mesh } from "three"; | |
import { useFrame } from "@react-three/fiber"; | |
import { useSpring, animated, config } from "@react-spring/three"; | |
export const Box = () => { | |
const [active, setActive] = useState(false); | |
const boxRef = useRef<Mesh>(null!); | |
const isHovered = useRef(false); | |
const starterRotation = [0, 1, 1]; | |
useFrame(() => { | |
if (!isHovered.current) { | |
boxRef.current.rotation.x += 0.01; | |
boxRef.current.rotation.y -= 0.01; | |
} | |
}); | |
const [{ rotation }, setSpring] = useSpring(() => ({ | |
rotation: [0, 0, 0] | |
})); | |
const springs = useSpring({ scale: active ? 1.5 : 1, config: config.wobbly }); | |
return ( | |
<animated.mesh | |
// @ts-ignore | |
rotation={rotation} | |
scale={springs.scale} | |
onClick={() => setActive(!active)} | |
onPointerOver={() => { | |
isHovered.current = true; | |
setSpring.start({ | |
from: { | |
rotation: [ | |
boxRef.current.rotation.x, | |
boxRef.current.rotation.y, | |
boxRef.current.rotation.z | |
] | |
}, | |
to: { | |
rotation: starterRotation | |
}, | |
config: { duration: 1000 } | |
}); | |
}} | |
onPointerLeave={() => { | |
isHovered.current = false; | |
}} | |
ref={boxRef} | |
> | |
<boxGeometry args={[2, 1, 2]} /> | |
<meshStandardMaterial color="royalblue" /> | |
</animated.mesh> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment