Gathering detailed insights and metrics for drei
Gathering detailed insights and metrics for drei
Gathering detailed insights and metrics for drei
Gathering detailed insights and metrics for drei
npm install drei
Typescript
Module System
Node Version
NPM Version
66.2
Supply Chain
85.8
Quality
76.6
Maintenance
50
Vulnerability
98.2
License
JavaScript (59.26%)
TypeScript (40.54%)
Shell (0.17%)
HTML (0.02%)
CSS (0.01%)
GLSL (0.01%)
Total Downloads
719,618
Last Day
161
Last Week
1,560
Last Month
7,551
Last Year
70,563
MIT License
9,028 Stars
2,214 Commits
758 Forks
49 Watchers
85 Branches
255 Contributors
Updated on Jul 01, 2025
Minified
Minified + Gzipped
Latest Version
2.2.21
Package Id
drei@2.2.21
Size
295.85 kB
NPM Version
7.4.0
Node Version
15.6.0
Published on
Jan 24, 2021
Cumulative downloads
Total Downloads
Last Day
-56.5%
161
Compared to previous day
Last Week
-25.7%
1,560
Compared to previous week
Last Month
17.8%
7,551
Compared to previous month
Last Year
19.6%
70,563
Compared to previous year
A growing collection of useful helpers and abstractions for react-three-fiber.
1npm install @react-three/drei
1import { PerspectiveCamera, PositionalAudio, ... } from '@react-three/drei'
A responsive THREE.PerspectiveCamera that can set itself as the default.
1<PerspectiveCamera 2 makeDefault // Registers it as the default camera system-wide (default=false) 3 {...props} // All THREE.PerspectiveCamera props are valid 4> 5 <mesh /> 6</PerspectiveCamera>
A responsive THREE.OrthographicCamera that can set itself as the default.
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.
Buffer-geometry short-cuts:
1<Plane args={[2, 2]} /> 2<Sphere> 3 <meshBasicMaterial attach="material" color="hotpink" /> 4</Sphere>
A box buffer geometry with rounded corners, done with extrusion.
1<RoundedBox 2 args={[1, 1, 1]} // Width, Height and Depth of the box 3 radius={0.05} // Border-Radius of the box 4 smoothness={4} // Optional, number of subdivisions 5 {...meshProps} // All THREE.Mesh props are valid 6> 7 <meshPhongMaterial attach="material" color="#f3f3f3" wireframe /> 8</RoundedBox>
1<ScreenQuad> 2 <myMaterial /> 3</ScreenQuad>
A triangle that fills the screen, ideal for full-screen fragment shader work (raymarching, postprocessing). ???? Why a triangle? https://www.cginternals.com/en/blog/2018-01-10-screen-aligned-quads-and-triangles.html ???? Use as a post processing mesh: https://medium.com/@luruke/simple-postprocessing-in-three-js-91936ecadfb7
Hi-quality text rendering w/ signed distance fields (SDF) and antialiasing, using troika-3d-text. All of troikas props are valid!
1<Text 2 color="black" // default 3 anchorX="center" // default 4 anchorY="middle" // default 5> 6 hello world! 7</Text>
Renders a THREE.Line2.
1<Line 2 points={[[0, 0, 0], ...]} // Array of points 3 color="black" // Default 4 lineWidth={1} // In pixels (default) 5 dashed={false} // Default 6 vertexColors={[[0, 0, 0], ...]} // Optional array of RGB values for each point 7 {...lineProps} // All THREE.Line2 props are valid 8 {...materialProps} // All THREE.LineMaterial props are valid 9/>
A wrapper around THREE.LOD (Level of detail).
1<Detailed 2 distances={[0, 10, 20]} // Camera distances, correspends to the # of the children 3 {...props} // All THREE.LOD props are valid 4> 5 <mesh geometry={highDetail} /> 6 <mesh geometry={mediumDetail} /> 7 <mesh geometry={lowDetail} /> 8</Detailed>
A wrapper around THREE.PositionalAudio. Add this to groups or meshes to tie them to a sound that plays when the camera comes near.
1<PositionalAudio 2 url="/sound.mp3" // Url of the sound file 3 distance={1} // Camera distance (default=1) 4 loop // Repat play (default=true) 5 {...props} // All THREE.PositionalAudio props are valid 6/>
Adds a <Plane />
that always faces the camera.
1<Billboard 2 follow={true} // Follow the camera (default=true) 3 lockX={false} // Lock the rotation on the x axis (default=false) 4 lockY={false} // Lock the rotation on the y axis (default=false) 5 lockZ={false} // Lock the rotation on the z axis (default=false) 6/>
Sets up a global cubemap, which affects scene.environment
, and optionally scene.background
. A selection of presets from HDRI Haven are available for convenience.
1<Environment 2 background={false} // Whether to affect scene.background 3 files={['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png']} // Array of cubemap files OR single equirectangular file 4 path={'/'} // Path to the above file(s) 5 preset={null} // Preset string (overrides files and path) 6/>
Abstraction around threes own EffectComposer.
1<Effects 2 multisamping={8} // Default, uses WebGL2 multisamping if available 3 renderIndex={1} // Default 4 disableGamma={false} // Default, would switch off the gamma-correction-pass 5 disableRenderPass={false} // Default, would remove the first scene-render-pass 6> 7 {/* Generic passes go here ... */} 8 <lUTPass attachArray="passes" lut={texture3D} /> 9</Effects>
A hook that abstracts AnimationMixer.
1const { nodes, materials, animations } = useGLTF(url) 2const { ref, mixer, names, actions, clips } = useAnimations(animations) 3useEffect(() => { 4 actions.jump.play() 5}) 6return ( 7 <mesh ref={ref} />
This material makes your geometry wobble and wave around. It was taken from the threejs-examples and adapted into a self-contained material.
1<mesh> 2 <boxBufferGeometry attach="geometry" /> 3 <MeshWobbleMaterial 4 attach="material" 5 factor={1} // Strength, 0 disables the effect (default=1) 6 speed={10} // Speed (default=1) 7 /> 8</mesh>
This material makes your geometry distort following simplex noise.
1<mesh> 2 <boxBufferGeometry attach="geometry" /> 3 <MeshDistortMaterial 4 attach="material" 5 distort={1} // Strength, 0 disables the effect (default=1) 6 speed={10} // Speed (default=1) 7 /> 8</mesh>
Adds a sky to your scene.
1<Sky 2 distance={450000} // Camera distance (default=450000) 3 sunPosition={[0, 1, 0]} // Sun position normal (defaults to inclination and azimuth if not set) 4 inclination={0} // Sun elevation angle from 0 to 1 (default=0) 5 azimuth={0.25} // Sun rotation around the Y axis from 0 to 1 (default=0.25) 6 {...props} // All three/examples/jsm/objects/Sky props are valid 7/>
Adds a blinking shader-based starfield to your scene.
1<Stars 2 radius={100} // Radius of the inner sphere (default=100) 3 depth={50} // Depth of area where stars should fit (default=50) 4 count={5000} // Amount of stars (default=5000) 5 factor={4} // Size factor (default=4) 6 saturation={0} // Saturation 0-1 (default=0) 7 fade // Faded dots (default=false) 8/>
A contact shadow implementation.
1<ContactShadows 2 opacity={1} 3 width={1} 4 height={1} 5 blur={1} // Amount of blue (default=1) 6 far={10} // Focal distance (default=10) 7 resolution={256} // Rendertarget resolution (default=256) 8/>
Injects percent closer soft shadows (pcss) into threes shader chunk.
1softShadows({ 2 frustrum: 3.75, // Frustrum width (default: 3.75) 3 size: 0.005, // World size (default: 0.005) 4 near: 9.5, // Near plane (default: 9.5) 5 samples: 17, // Samples (default: 17) 6 rings: 11, // Rings (default: 11) 7})
Creates a THREE.ShaderMaterial for you with easier handling of uniforms, which are also automatically declared as setter/getters on the object.
1import { extend } from 'react-three-fiber' 2import glsl from 'babel-plugin-glsl/macro' 3 4const ColorShiftMaterial = shaderMaterial( 5 { time: 0, color: new THREE.Color(0.2, 0.0, 0.1) }, 6 // vertex shader 7 glsl` 8 varying vec2 vUv; 9 void main() { 10 vUv = uv; 11 gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); 12 } 13 `, 14 // fragment shader 15 glsl` 16 uniform float time; 17 uniform vec3 color; 18 varying vec2 vUv; 19 void main() { 20 gl_FragColor.rgba = vec4(0.5 + 0.3 * sin(vUv.yxx + time) + color, 1.0); 21 } 22 ` 23) 24 25extend({ ColorShiftMaterial }) 26 27// in your component 28<mesh> 29 <colorShiftMaterial attach="material" color="hotpink" time={1} /> 30</mesh>
Allows you to forward contexts provided above the <Canvas />
to be consumed from within the <Canvas />
normally
1function SceneWrapper() { 2 // bridge any number of contexts 3 const ContextBridge = useContextBridge(ThemeContext, GreetingContext) 4 return ( 5 <Canvas> 6 <ContextBridge> 7 <Scene /> 8 </ContextBridge> 9 </Canvas> 10 ) 11} 12 13function Scene() { 14 // we can now consume a context within the Canvas 15 const theme = React.useContext(ThemeContext) 16 const greeting = React.useContext(GreetingContext) 17 return ( 18 //... 19 ) 20}
Creates a THREE.WebGLRenderTarget
or THREE.WebGLMultisampleRenderTarget
.
1const target = useFBO(
2 // width: 500, height: 500,
3 // width and height are optional and defaulted to the viewport size
4 // multiplied by the renderer pixel ratio, and recalculated whenever the
5 // viewport size changes.
6 {
7 multisample: true, // if the renderer supports webGL2, it will return a WebGLMultisampleRenderTarget
8 stencilBuffer: false // you can pass any options supported by THREE.WebGLRenderTarget
9 }
10)
The rendertarget is automatically disposed when unmounted.
Allows you to tie HTML content to any object of your scene. It will be projected to the objects whereabouts automatically.
1<Html 2 prepend // Project content behind the canvas (default: false) 3 center // Adds a -50%/-50% css transform (default: false) 4 fullscreen // Aligns to the upper-left corner, fills the screen (default:false) 5 scaleFactor={10} // If set (default: undefined), children will be scaled by this factor, and also by distance to a PerspectiveCamera. 6 zIndexRange={[100, 0]} // Z-order range (default=[16777271, 0]) 7 portal={domnodeRef} // Reference to target container (default=undefined) 8 {...groupProps} // All THREE.Group props are valid 9 {...divProps} // All HTMLDivElement props are valid 10> 11 <h1>hello</h1> 12 <p>world</p> 13</Html>
Easily add reflection to any object
1<Reflector> 2 <planeBufferGeometry args={[2, 5]} attach="geometry" /> 3</Reflector>
A cheap canvas-texture-based circular gradient.
1<Shadow 2 color="black" // Color (default:black) 3 colorStop={0} // First gradient-stop (default:0) 4 opacity={0.5} // Alpha (default:0.5) 5 fog={false} // Reacts to fog (default=false) 6/>
Adds stats to document.body. It takes over the render-loop!
1<Stats 2 showPanel={0} // Start-up panel (default=0) 3 className="stats" // Optional className to add to the stats container dom element 4 {...props} // All stats.js props are valid 5/>
You can choose to mount Stats to a different DOM Element - for example, for custom styling:
1const node = useRef(document.createElement('div')) 2 3useEffect(() => { 4 node.current.id = 'test' 5 document.body.appendChild(node.current) 6 7 return () => document.body.removeChild(node.current) 8}, []) 9 10return <Stats parent={parent} />
Calculates a boundary box and centers its children accordingly.
1<Center> 2 <mesh /> 3</Center>
A very fast, but often good-enough bounds-only raycast for meshes. You can use this if performance has precidence over pointer precision.
1<mesh raycast={meshBounds} />
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).
1<mesh raycast={useCamera(customCamera)} />
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.
1const mesh = useRef() 2useHelper(mesh, BoxHelper, 'cyan')
This hook uses DetectGPU by @TimvanScherpenzeel to determine what tier should be assigned to the user's GPU.
???? This hook CAN be used outside the react-three-fiber Canvas
.
1const GPUTier = useDetectGPU() 2 3// show a fallback for mobile or lowest tier GPUs 4return ( 5 {(GPUTier.tier === "0" || GPUTier.isMobile) ? <Fallback /> : <Canvas>...</Canvas>
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]
.
1const scale = useAspect( 2 "cover", // Aspect ratio: cover | ... more to come, PR's welcome ;) 3 1024, // Pixel-width 4 512, // Pixel-height 5 1 // Optional scaling factor 6) 7return ( 8 <mesh scale={scale}> 9 <planeBufferGeometry /> 10 <meshBasicMaterial map={imageTexture} />
Given a curve will replace the children of this component with a mesh that move along said curve calling the property moveAlongCurve
on the passed ref. Uses three's Curve Modifier
1const curveRef = useRef() 2 3const curve = React.useMemo(() => new THREE.CatmullRomCurve3([...handlePos], true, 'centripetal'), [handlePos]) 4 5return ( 6 <CurveModifier ref={curveRef} curve={curve}> 7 <mesh> 8 <boxBufferGeometry args={[10, 10]} /> 9 </mesh> 10 </CurveModifier> 11)
This hook mutates a mesh geometry using three's Edge Split modifier.
1const meshRef = useEdgeSplit(Math.PI / 2) 2 3return ( 4 <mesh ref={meshRef}> 5 <boxBufferGeometry args={[10, 10]} /> 6 </mesh> 7)
This hook mutates a mesh geometry using three's Subdivision modifier.
???? Vertex count is quadrupled for each subdivision.
1const meshRef = useSubdivision(4) 2 3return ( 4 <mesh ref={meshRef}> 5 <boxBufferGeometry args={[10, 10]} /> 6 </mesh> 7)
This hook mutates a mesh geometry using three's Simplification modifier.
???? The simplification code is based on this algorithm.
1const meshRef = useSimplification(0.5) // the vertices will be halved 2 3return ( 4 <mesh ref={meshRef}> 5 <octahedronBufferGeometry args={[2, 5]} /> 6 </mesh> 7)
This hook mutates a mesh geometry using three's Tessellation modifier. It will break-up faces withe edge longer than the maxEdgeLength parameter.
1const meshRef = useTessellation(
2 2, // passes - number of times the geometry will be subdivided
3 8 // maxEdgeLength - faces with edges longer than this number will be broken up
4)
5
6return (
7 <mesh ref={meshRef}>
8 <octahedronBufferGeometry args={[2, 2]} />
9 </mesh>
10)
A convenience hook that uses useLoader
and GLTFLoader
, it defaults to CDN loaded draco binaries (https://www.gstatic.com/draco/v1/decoders/
) which are only loaded for compressed models.
1// Loads model, uses CDN draco when needed 2useGLTF(url) 3 4// Use local draco binaries from a custom path 5useGLTF(url, '/draco-gltf') 6 7// Preload asset (you would do this in global space, not inside a component!) 8useGLTF.preload(url)
A convenience hook that uses useLoader
and FBXLoader
:
1useFBX(url)
2
3function SuzanneFBX() {
4 let fbx = useFBX('suzanne/suzanne.fbx')
5 // wrap fbx in primitive.
6 return <primitive object={fbx} dispose={null} />
7}
A convenience hook that uses useLoader
and TextureLoader
1const texture = useTexture(url) 2 3const [texture1, texture2] = useTexture([texture1, texture2])
A convenience hook that uses useLoader
and CubeTextureLoader
1const envMap = useCubeTexture(['px.png', 'nx.png', 'py.png', 'ny.png', 'pz.png', 'nz.png'], { path: 'cube/' })
A convenience hook that wraps THREE.DefaultLoadingManager
's progress status.
1function Loader() { 2 const { active, progress, errors, item, loaded, total } = useProgress() 3 return <Html center>{progress} % loaded</Html> 4} 5 6return ( 7 <Suspense fallback={<Loader />}> 8 <AsyncModels /> 9 </Suspense> 10)
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.
1const 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.
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.
1<Canvas> 2 <Suspense fallback={null}> 3 <AsyncModels /> 4 </Suspense> 5</Canvas> 6<Loader />
You can override styles, too.
1<Loader 2 containerStyles={...container} // Flex layout styles 3 innerStyles={...inner} // Inner container styles 4 barStyles={...bar} // Loading-bar styles 5 dataStyles={...data} // Text styles 6 dataInterpolation={(p) => `Loading ${p.toFixed(2)}%`} // Text 7 initialState={(active) => active} // Initial black out state 8>
Loads matcap textures from this repository: https://github.com/emmelleppi/matcaps
(It is a fork of this repository: https://github.com/nidorx/matcaps)
1const [matcap, url] = useMatcapTexture(
2 0, // index of the matcap texture https://github.com/emmelleppi/matcaps/blob/master/matcap-list.json
3 1024 // size of the texture ( 64, 128, 256, 512, 1024 )
4)
5
6return (
7 ...
8 <meshMatcapMaterial matcap={matcap} />
9 ...
10)
???? You can also use the exact name of the matcap texture, like so:
1const [matcap] = useMatcapTexture('3E2335_D36A1B_8E4A2E_2842A5')
???? Use the url
to download the texture when you are ready for production!
Loads normal textures from this repository: https://github.com/emmelleppi/normal-maps
1const [normalMap, url] = useNormalTexture(
2 1, // index of the normal texture - https://github.com/emmelleppi/normal-maps/blob/master/normals.json
3 // second argument is texture attributes
4 {
5 offset: [0, 0],
6 repeat: [normRepeat, normRepeat],
7 anisotropy: 8
8 }
9)
10
11return (
12 ...
13 <meshStandardMaterial normalMap={normalMap} />
14 ...
15)
16
No vulnerabilities found.
Reason
14 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
binaries present in source code
Details
Reason
Found 13/29 approved changesets -- score normalized to 4
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
branch protection not enabled on development/release branches
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
project is not fuzzed
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
17 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-06-23
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More