GitHub - drcmda/react-three-fiber: ?React-fiber renderer for THREE.js
source link: https://github.com/drcmda/react-three-fiber
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
readme.md
This demo is real, click it!
npm install react-three-fiber
React-three-fiber is a small React renderer for THREE-js. Regular THREE can sometimes produce rather complex code due to everything being non-reactive, mutation and imperative layout-inflating.
Driving something like THREE as a render-target makes so much sense if you think about it, it makes building scene graphs easier since content can be componentized declaratively with clean, reactive semantics. This also opens up the eco system, you can now apply generic packages for state, animation, gestures, etc.
Objects and attributes
You can access the entirety of THREE's object catalogue as well as all of their properties. If you want to reach into nested attributes (for instance: mesh.rotation.x
), just use dash-case (<mesh rotation-x={...} />
). This renderer doesn't change THREE's semantics other than using JSX, it does not introduce any regression or limit.
Events
THREE objects that implement their own raycast
method (for instance meshes, lines, etc) can be interacted with by declaring events on the object. For now that's hovering state, clicks and (soon) drag'n'drop.
Difference to react-three, react-three-renderer, react-three-renderer-fiber
Not trying to step on anyones toes, from how it looks to me, some of the above mentioned aren't maintained any longer, or chained to React 15, or highly specific and/or complex. This lib just ships a small reconciler config with a few additions for interaction. It does not know, care about or duplicate THREE's object catalogue, it uses a few heuristics to support attributes generically.
Todo
-
There are still lots of objects you need to create outside of the render tree (geometries, materials, vectors, etc). THREE usually wouldn't allow them inside the scene. I am still thinking on how to solve this, i'd like them to be in the render-tree so that they can be reactive. ?
-
Not sure it's a good idea to abstract the renderer away with
Canvas
, probably will be possible to declaratively define it soon.
Example
import { Canvas } from 'react-three-fiber' function App() { return ( <Canvas> <group> <mesh // You get full access to the instance with a reference ref={ref => console.log(ref)} // You can set any object on the instance geometry={new THREE.BoxGeometry(1, 1, 1)} material={new THREE.MeshBasicMaterial({ color: 0x00ff00, transparent: true })} // Read-only props in THREE that have a ".set" function can still be written to scale={new Vector3(2, 2, 2)} // Or by an array that gets spread over the internal ".set(...)" function scale={[2, 2, 2]} // You are also allowed to pierce into the instance scale-x={3} // ... which works for everything, even materials material-color={new THREE.Color(0xff0000)} // And since it's using ".set(...)", you can feed it all the values it can take material-color={'rgb(100, 200, 50)'} // Interaction comes inbuilt onHover={e => console.log('hovered', e)} onUnhover={e => console.log('unhovered', e)} onClick={e => console.log('clicked', e)} onPick={e => console.log('picked', e)} onDrag={e => console.log('dragged', e)} onDrop={e => console.log('dropped', e)} /> <line geometry={new THREE.Geometry()} material={new THREE.LineBasicMaterial({ color: 0xffffff })} // With piercing you can even declare mesh/vertice data declaratively geometry-vertices={[[-1,0,0],[0,1,0],[1,0,0]].map(v => new THREE.Vector3(...v))} /> </group> </Canvas> ) } ReactDOM.render(<App />, document.getElementById('root'))
Custom config
GL-props, camera and some events allow you to customize the render-session.
function App() { const cam = useRef() return ( <Canvas camera={cam} glProps={ antialias: true } onCreated={(gl, camera, pool scene) => console.log("gl created")} onUpdate={(gl, camera, pool scene) => console.log("i'm in the render-loop")}> <perspectiveCamera ref={cam} fov={75} near={0.1} far={1000} /> <SpinningBox /> </Canvas> ) }
Extending or using arbitrary objects
Wrap the primitive
placeholder around custom or extended THREE-objects that you want to render into the scene-graph.
const geo = new THREE.BoxGeometry(10, 0.1, 0.1) const mat = new THREE.MeshBasicMaterial({ transparent: true }) const msh = new MyExtendedMesh(geo, mat) return <primitive object={msh} />
Hooking into the render loop
Sometime you're running effects, postprocessing, etc that needs to get updated. You can fetch the renderer, the camera, scene, and a render-loop subscribe from context to do this. subscribe()
returns the unsub function, so you can nicely use it in effects for auto-cleanup.
import { Canvas, context } from 'react-three-fiber' function App() { const { subscribe, renderer, scene, camera } = useContext(context) useEffect(() => subscribe(() => console.log("i'm in the render-loop")), []) return <group /> }
Custom canvas
The default Canvas
component is just a effect around the canvas element. You can implement your own.
import * as THREE from 'three' import React, { useRef, useEffect } from 'react' import { render, unmountComponentAtNode } from 'react-three-fiber' export function Canvas({ children }) { const canvasRef = useRef() const active = useRef(true) useEffect(() => { // Create THREE renderer const renderer = new THREE.WebGLRenderer({ canvas: canvasRef.current }) const scene = new THREE.Scene() const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000) renderer.setSize(window.innerWidth, window.innerHeight) camera.position.z = 5 // Create render-loop const renderLoop = function() { if (!active.current) return requestAnimationFrame(renderLoop) renderer.render(scene, camera) } // Render children into scene render(children, scene) // Start render-loop renderLoop() // Clean-up () => { active.current = false unmountComponentAtNode(scene) } }, []) // Render canvas container into the DOM return <canvas ref={canvasRef} /> }
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK