react-three-fiber用于 Three.js 的 React 渲染器
react-three-fiber 是針對(duì) Web 和 react-native 上的 threejs 的 React 渲染器。
特點(diǎn)
-
使用可重用的組件以聲明方式構(gòu)建動(dòng)態(tài)場(chǎng)景圖,使 Threejs 的處理變得更加輕松,并使代碼庫更加整潔。這些組件對(duì)狀態(tài)變化做出反應(yīng),具有開箱即用的交互性。
-
在 threejs 中工作的所有內(nèi)容都將在這里工作。它不針對(duì)特定的 Threejs 版本,也不需要更新以修改,添加或刪除上游功能。
-
渲染性能與 threejs 和 GPU 相仿。組件參與 React 之外的 renderloop 時(shí),沒有任何額外開銷。
使用示例
import ReactDOM from 'react-dom'
import React, { useRef, useState } from 'react'
import { Canvas, useFrame } from 'react-three-fiber'
function Box(props) {
// This reference will give us direct access to the mesh
const mesh = useRef()
// Set up state for the hovered and active state
const [hovered, setHover] = useState(false)
const [active, setActive] = useState(false)
// Rotate mesh every frame, this is outside of React without overhead
useFrame(() => {
mesh.current.rotation.x = mesh.current.rotation.y += 0.01
})
return (
<mesh
{...props}
ref={mesh}
scale={active ? [1.5, 1.5, 1.5] : [1, 1, 1]}
onClick={(event) => setActive(!active)}
onPointerOver={(event) => setHover(true)}
onPointerOut={(event) => setHover(false)}>
<boxBufferGeometry args={[1, 1, 1]} />
<meshStandardMaterial color={hovered ? 'hotpink' : 'orange'} />
</mesh>
)
}
ReactDOM.render(
<Canvas>
<ambientLight />
<pointLight position={[10, 10, 10]} />
<Box position={[-1.2, 0, 0]} />
<Box position={[1.2, 0, 0]} />
</Canvas>,
document.getElementById('root')
)
評(píng)論
圖片
表情
