A growing collection of useful helpers and abstractions for react-three-fiber, saving you some boilerplate.
If you find yourself repeating set-up code often and if it's generic enough, add it here, everyone benefits!
Requirements
- Types
- ForwardRefs if possible, so that objects can be referenced back
- Invalidate frames on any movement for those using invalidateFrameloop
- Cleanup on unmount, no left-overs, restore previous states
npm install drei
import { ... } from 'drei'
Live Playground
For examples of drei in action, visit https://drei.react-spring.io/
Or, run the demo storybook on your computer:
git clone https://github.com/react-spring/drei
cd drei
npm install
npm run storybook
Index
Exports
Cameras
PerspectiveCamera
A responsive THREE.PerspectiveCamera that can set itself as the default.
<PerspectiveCamera
makeDefault
{...props}
>
<mesh />
</PerspectiveCamera>
OrthographicCamera
A responsive THREE.OrthographicCamera that can set itself as the default.
Controls
If available controls have damping enabled by default, they manage their own updates, remove themselves on unmount, are compatible with the invalidateFrameloop
canvas-flag. They inherit all props from their underlying THREE controls.
OrbitControls
MapControls
TrackballControls
FlyControls
DeviceOrientationControls
TransformControls
PointerLockControls
Shapes
Buffer-geometry short-cuts:
<Plane args={[2, 2]} />
<Sphere>
<meshBasicMaterial attach="material" color="hotpink" />
</Sphere>
Plane
Box
Sphere
Circle
Cone
Cylinder
Tube
Torus
TorusKnot
Ring
Tetrahedron
Polyhedron
Icosahedron
Octahedron
Dodecahedron
Extrude
Lathe
Parametric
RoundedBox
A box buffer geometry with rounded corners, done with extrusion.
<RoundedBox
args={[1, 1, 1]}
radius={0.05}
smoothness={4}
{...meshProps}
>
<meshPhongMaterial attach="material" color="#f3f3f3" wireframe />
</RoundedBox>
Abstractions
Text
Hi-quality text rendering w/ signed distance fields (SDF) and antialiasing, using troika-3d-text. All of troikas props are valid!
<Text
color="black"
anchorX="center"
anchorY="middle"
>
hello world!
</Text>
Line
Renders a THREE.Line2.
<Line
points={[[0, 0, 0], ...]}
color="black"
lineWidth={1}
dashed={false}
vertexColors={[[0, 0, 0], ...]}
{...lineProps}
{...materialProps}
/>
Detailed
A wrapper around THREE.LOD (Level of detail).
<Detailed
distances={[0, 10, 20]}
{...props}
>
<mesh geometry={highDetail} />
<mesh geometry={mediumDetail} />
<mesh geometry={lowDetail} />
</Detailed>
PositionalAudio
A wrapper around THREE.PositionalAudio. Add this to groups or meshes to tie them to a sound that plays when the camera comes near.
<PositionalAudio
url="/sound.mp3"
distance={1}
loop
{...props}
/>
StandardEffects
Standard Effects has been removed from drei in favour of (react-spring/react-postprocessing)[https://github.com/react-spring/react-postprocessing]
Billboard
Adds a <Plane />
that always faces the camera.
<Billboard
follow={true}
lockX={false}
lockY={false}
lockZ={false}
/>
Shaders
MeshWobbleMaterial
This material makes your geometry wobble and wave around. It was taken from the threejs-examples and adapted into a self-contained material.
<mesh>
<boxBufferGeometry attach="geometry" />
<MeshWobbleMaterial
attach="material"
factor={1} // Strength, 0 disables the effect (default=1)
speed={10} // Speed (default=1)
/>
</mesh>
MeshDistortMaterial
This material makes your geometry distort following simplex noise.
<mesh>
<boxBufferGeometry attach="geometry" />
<MeshDistortMaterial
attach="material"
distort={1} // Strength, 0 disables the effect (default=1)
speed={10} // Speed (default=1)
/>
</mesh>
Sky
Adds a sky to your scene.
<Sky
distance={450000}
sunPosition={[0, 1, 0]}
{...props}
/>
Stars
Adds a blinking shader-based starfield to your scene.
<Stars
radius={100}
depth={50}
count={5000}
factor={4}
saturation={0}
fade
/>
softShadows
Injects percent closer soft shadows (pcss) into threes shader chunk.
softShadows({
frustrum: 3.75,
size: 0.005,
near: 9.5,
samples: 17,
rings: 11,
})
shaderMaterial
Creates a THREE.ShaderMaterial for you with easier handling of uniforms, which are also automatically declared as setter/getters on the object.
import { extend } from "react-three-fiber"
import glsl from "babel-plugin-glsl/macro"
const ColorShiftMaterial = shaderMaterial(
{ time: 0, color: new THREE.Color(0.2, 0.0, 0.1) },
glsl`
varying vec2 vUv;
void main() {
vUv = uv;
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
}
`,
glsl`
uniform float time;
uniform vec3 color;
varying vec2 vUv;
void main() {
gl_FragColor.rgba = vec4(0.5 + 0.3 * sin(vUv.yxx + time) + color, 1.0);
}
`
)
extend({ ColorShiftMaterial })
<mesh>
<colorShiftMaterial attach="material" color="hotpink" time={1} />
Misc
Html
Allows you to tie HTML content to any object of your scene. It will be projected to the objects whereabouts automatically.
<Html
prepend
center
fullscreen
scaleFactor={10}
zIndexRange={[100, 0]}
portal={domnodeRef}
{...groupProps}
{...divProps}
>
<h1>hello</h1>
<p>world</p>
</Html>
Reflector
Easily add reflection to any object
<Reflector>
<planeBufferGeometry args={[2, 5]} attach="geometry" />
</Reflector>
Shadow
A cheap canvas-texture-based circular gradient.
<Shadow
color="black"
colorStop={0}
opacity={0.5}
fog={false}
/>
Stats
Adds stats to document.body. It takes over the render-loop!
<Stats
showPanel={0}
className="stats"
{...props}
/>
You can choose to mount Stats to a different DOM Element - for example, for custom styling:
const node = useRef(document.createElement('div'))
useEffect(() => {
node.current.id = 'test'
document.body.appendChild(node.current)
return () => document.body.removeChild(node.current)
}, [])
return <Stats parent={parent} />
meshBounds
A very fast, but often good-enough bounds-only raycast for meshes. You can use this if performance has precidence over pointer precision.
<mesh raycast={meshBounds} />
useCamera
A hook for the rare case when you are using non-default cameras for heads-up-displays or portals, and you need events/raytracing to function properly (raycasting uses the default camera otherwise).
<mesh raycast={useCamera(customCamera)} />
useHelper
A hook for a quick way to add helpers to existing nodes in the scene. It handles removal of the helper on unmount and auto-updates it by default.
const mesh = useRef()
useHelper(mesh, BoxHelper, 'cyan')
useAspect
This hook calculates aspect ratios (for now only what in css would be image-size: cover
is supported). You can use it to make an image fill the screen. It is responsive and adapts to viewport resize. Just give the hook the image bounds in pixels. It returns an array: [width, height, 1]
.
const scale = useAspect(
"cover",
1024,
512,
1
)
return (
<mesh scale={scale}>
<planeBufferGeometry />
<meshBasicMaterial map={imageTexture} />
Modifiers
useSubdivision
This hook mutates a mesh geometry using three's Subdivision modifier.
š Vertex count is quadrupled for each subdivision.
const meshRef = useSubdivision(4)
return (
<mesh ref={meshRef}>
<boxBufferGeometry args={[10, 10]} />
</mesh>
)
useSimplification
This hook mutates a mesh geometry using three's Simplification modifier.
š The simplification code is based on this algorithm.
const meshRef = useSimplification(0.5)
return (
<mesh ref={meshRef}>
<octahedronBufferGeometry args={[2, 5]} />
</mesh>
)
useTessellation
This hook mutates a mesh geometry using three's Tessellation modifier. It will break-up faces withe edge longer than the maxEdgeLength parameter.
const meshRef = useTessellation(
2,
8,
)
return (
<mesh ref={meshRef}>
<octahedronBufferGeometry args={[2, 2]} />
</mesh>
)
Loaders
useGLTFLoader
A convenience hook that uses useLoader
, GLTFLoader
and draco
:
useGLTFLoader(
url,
true
)
useGLFTLoader(
url,
'/my-draco-binaries'
)
useTextureLoader
A convenience hook that uses useLoader
and TextureLoader
const texture = useTextureLoader(url)
const [texture1, texture2] = useTextureLoader([texture1, texture2])
useCubeTextureLoader
A convenience hook that uses useLoader
and CubeTextureLoader
const envMap = useCubeTextureLoader(
['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'],
{ path: 'cube/' }
)
draco
Adds the Draco extension to your GLTFLoader, to be used in conjuction with useLoader
and GLTFLoader
when more control is needed.
useLoader(
GLTFLoader,
url,
draco(
'/draco-gtltf/'
)
)
useProgress
A convenience hook that wraps THREE.DefaultLoadingManager
's progress status.
function Loader() {
const { active, progress, errors, item, loaded, total } = useProgress()
return <Html center>{progress} % loaded</Html>
}
<Suspense fallback={<Loader />}>
<AsyncModels />
</Suspense>
If you don't want your progress component to re-render on all changes you can be specific as to what you need, for instance if the component is supposed to collect errors only. Look into zustand for more info about selectors.
const errors = useProgress(state => state.errors)
š Note that your loading component does not have to be a suspense fallback. You can use it anywhere, even in your dom tree, for instance for overlays.
ā”ļø Prototyping
Loader
A quick and easy loading overlay component that you can drop on top of your canvas. It will show an animated loadingbar and a percentage.
<Canvas>
<Suspense fallback={null}>
<AsyncModels />
</Suspense>
</Canvas>
<Loader />
You can override styles, too.
<Loader
containerStyles={...container}
innerStyles={...inner}
barStyles={...bar}
dataStyles={...data}
dataInterpolation={(p) => `Loading ${p.toFixed(2)}%`}
initialState={(active) => active}
>
useMatcapTexture
Loads matcap textures from this repository: https://github.com/emmelleppi/matcaps
(It is a fork of this repository: https://github.com/nidorx/matcaps)
const [matcap, url] = useMatcapTexture(
0,
1024
)
return (
...
<meshMatcapMaterial matcap={matcap} />
...
)
š You can also use the exact name of the matcap texture, like so:
const [matcap] = useMatcapTexture("3E2335_D36A1B_8E4A2E_2842A5");
š Use the url
to download the texture when you are ready for production!
useNormalTexture
Loads normal textures from this repository: https://github.com/emmelleppi/normal-maps
const [normalMap, url] = useNormalTexture(
1,
{
offset: [0, 0],
repeat: [normRepeat, normRepeat],
anisotropy: 8
}
)
return (
...
<meshStandardMaterial normalMap={normalMap} />
...
)