Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

drei

Package Overview
Dependencies
Maintainers
1
Versions
97
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

drei

useful add-ons for react-three-fiber

  • 0.0.71
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
1.6K
increased by33.9%
Maintainers
1
Weekly downloads
 
Created
Source

Build Status npm version npm

logo

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
# Using npm
npm i drei --save

# Using yarn
yarn add drei
import { ... } from 'drei'
Live Playground

For examples of drei in action, visit https://drei-storybook.netlify.app/.

OR

Run the demo storybook on your computer:

Index

  • Cameras

    • <PerspectiveCamera/>
    • <OrthographicCamera/>
  • Controls

    • <OrbitControls/>
    • <FlyControls/>
    • <MapControls/>
    • <DeviceOrientationControls/>
    • <TrackballControls/>
    • <TransformControls/>
  • Shapes

    • <Plane/>, <Box/>, <Sphere/>, <Circle/>, <Cone/>, <Cylinder/>, <Tube/>, <Torus/>, <TorusKnot/>, <Ring/>, <Tetrahedron/>, <Polyhedron/>, <Icosahedron/>, <Octahedron/>, <Dodecahedron/>, <Extrude/>, <Lathe/>, <Parametric/>
  • Abstractions

    • <Text/>
    • <Line/>
    • <Detailed/>
    • <PositionalAudio/>
    • <StandardEffects/>
  • Shaders

    • <MeshWobbleMaterial/>
    • <MeshDistortMaterial/>
    • <Sky/>
    • <Stars/>
    • softShadows()
  • Misc

    • <Html/>
    • <Shadow/>
    • <Stats/>
    • meshBounds()
    • useCamera()
    • useHelper()
    • useAspect()
    • <Reflector/>
  • Loaders

    • draco()
    • useGLTFLoader()
    • useTextureLoader()
    • useCubeTextureLoader()

Exports

Cameras

⚡️ <PerspectiveCamera/>

A responsive THREE.PerspectiveCamera that can set itself as the default.

<PerspectiveCamera
  makeDefault // Registers it as the default camera system-wide (default=false)
  {...props} // All THREE.PerspectiveCamera props are valid
>
  <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/>
⚡️ <DeviceOrientationControls/>
⚡️ <TransformControls/>

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/>

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" // default
  anchorX="center" // default
  anchorY="middle" // default
>
  hello world!
</Text>
⚡️ <Line/>

Renders a THREE.Line2.

<Line
  points={[[0, 0, 0], ...]}       // Array of points
  color="black"                   // Default
  linewidth={1}                   // In pixels (default)
  dashed={false}                  // Default
  vertexColors={[[0, 0, 0], ...]} // Optional array of RGB values for each point
  {...lineProps}                  // All THREE.Line2 props are valid
  {...materialProps}              // All THREE.LineMaterial props are valid
/>
⚡️ <Detailed>

A wrapper around THREE.LOD (Level of detail).

<Detailed
  distances={[0, 10, 20]} // Camera distances, correspends to the # of the children
  {...props} // All THREE.LOD props are valid
>
  <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" // Url of the sound file
  distance={1} // Camera distance (default=1)
  loop // Repat play (default=true)
  {...props} // All THREE.PositionalAudio props are valid
/>
⚡️ <StandardEffects/>

Adds ambient-occlusion, bloom and SMAA using the postprocessing library.

⚠️ AO relies on the depthbuffer! Make sure your near and far clipping planes are narrow enough, or use <Canvas gl={{ logarithmicDepthBuffer: true }} .../>.

<StandardEffects
  smaa // Can be a boolean (default=true)
  ao // Can be a boolean or all valid postprocessing AO props (default=true)
  bloom // Can be a boolean or all valid postprocessing Bloom props (default=true)
  edgeDetection={0.1} // SMAA precision (default=0.1)
  bloomOpacity={1} // Bloom blendMode opacity (default=1)
  effects={() => [...fx]} // Define your own: ([smaa, ao, bloom]) => [...effects] (default=undefined)
/>

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} // Camera distance (default=450000)
  sunPosition={[0, 1, 0]} // Sun position normal (default=[0, 1, 0])
  {...props} // All three/examples/jsm/objects/Sky props are valid
/>
⚡️ <Stars/>

Adds a blinking shader-based starfield to your scene.

<Stars
  radius={100} // Radius of the inner sphere (default=100)
  depth={50} // Depth of area where stars should fit (default=50)
  count={5000} // Amount of stars (default=5000)
  factor={4} // Size factor (default=4)
  saturation={0} // Saturation 0-1 (default=0)
  fade // Faded dots (default=false)
/>
⚡️ softShadows()

Injects percent closer soft shadows (pcss) into threes shader chunk.

softShadows({
  frustrum: 3.75, // Frustrum width (default: 3.75)
  size: 0.005, // World size (default: 0.005)
  near: 9.5, // Near plane (default: 9.5)
  samples: 17, // Samples (default: 17)
  rings: 11, // Rings (default: 11)
})

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 // Project content behind the canvas (default: false)
  center // Adds a -50%/-50% css transform (default: false)
  fullscreen // Aligns to the upper-left corner, fills the screen (default:false)
  scaleFactor={10} // If set (default: undefined), children will be scaled by this factor, and also by distance to a PerspectiveCamera.
  zIndexRange={[100, 0]} // Z-order range (default=[16777271, 0])
  portal={domnodeRef} // Reference to target container (default=undefined)
  {...groupProps} // All THREE.Group props are valid
  {...divProps} // All HTMLDivElement props are valid
>
  <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" // Color (default:black)
  colorStop={0} // First gradient-stop (default:0)
  opacity={0.5} // Alpha (default:0.5)
  fog={false} // Reacts to fog (default=false)
/>
⚡️ <Stats/>

Adds stats to document.body. It takes over the render-loop!

<Stats
  showPanel={0} // Start-up panel (default=0)
  className="stats" // Optional className to add to the stats container dom element
  {...props} // All stats.js props are valid
/>

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",                  // Aspect ratio: cover | ... more to come, PR's welcome ;)
  1024,                     // Pixel-width
  512,                      // Pixel-height
  1                         // Optional scaling factor
)
return (
  <mesh scale={scale}>
    <planeBufferGeometry />
    <meshBasicMaterial map={imageTexture} />

⚡️ Loaders

⚡️ useGLTFLoader()

A convenience hook that uses useLoader, GLTFLoader and draco:

useGLTFLoader(
  url,
  true // use draco binaries in /draco-gltf/
)

useGLFTLoader(
  url,
  '/my-draco-binaries' // use draco binaries from a custom path
)
⚡️ 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/' // Path to the Draco binaries (default='/draco-gtltf/')
  )
)

Keywords

FAQs

Package last updated on 05 Aug 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc