不明白的知识先放在一边,激发兴趣是第一步,所以不必纠结代码的细节,相信我你很快就会爱上这种感觉!!!
今天,我们将更进一步,将上一篇中vite + npm
传统 Three.js 原生代码完整 重构为 react-three-fiber 风格 ✅
本文将带你完成以下目标:
推荐网站 | 地址 |
---|---|
官方文档 | https://r3f.docs.pmnd.rs/getting-started |
优秀中文文档 | https://fiber.framer.wiki/Introduction |
react-three-fiber
是一个将 Three.js 映射为 React 声明式组件的库,优点包括:
npm create vite@latest r3f-demo --template react
cd r3f-demo
npm install
npm install three @react-three/fiber @react-three/drei
src/
├── App.jsx
├── components/
│ ├── Dodecahedron.jsx
│ ├── BaseBox.jsx
│ └── Lights.jsx
└── main.jsx
App.jsx
import { Canvas } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import Dodecahedron from './components/Dodecahedron';
import BaseBox from './components/BaseBox';
import Lights from './components/Lights';
export default function App() {
return (
<Canvas
camera={{ position: [0, 0, 5], fov: 75 }}
style={{ width: '100vw', height: '100vh' }}
>
<color attach="background" args={['#f0f0f0']} />
<Lights />
<Dodecahedron />
<BaseBox />
<OrbitControls enableDamping dampingFactor={0.05} />
</Canvas>
);
}
Dodecahedron.jsx
import { useRef } from 'react';
import { useFrame } from '@react-three/fiber';
export default function Dodecahedron() {
const ref = useRef();
useFrame(() => {
ref.current.rotation.x += 0.01;
ref.current.rotation.y += 0.01;
});
return (
<mesh ref={ref}>
<dodecahedronGeometry />
<meshLambertMaterial
color="#468585"
emissive="#468585"
/>
</mesh>
);
}
BaseBox.jsx
import { useRef } from 'react';
import { useFrame } from '@react-three/fiber';
export default function BaseBox() {
const ref = useRef();
useFrame(() => {
ref.current.rotation.y += 0.01;
});
return (
<mesh ref={ref} position={[0, -1.5, 0]}>
<boxGeometry args={[2, 0.1, 2]} />
<meshLambertMaterial
color="#b4b4b3"
emissive="#b4b4b3"
/>
</mesh>
);
}
Lights.jsx
export default function Lights() {
return (
<>
<ambientLight intensity={0.3} />
<spotLight
color="#006769"
intensity={100}
position={[1, 1, 1]}
castShadow
/>
</>
);
}
你现在应该能看到:
一个旋转的 十二面体
一个缓慢转动的 底座
柔和背景光与 聚光灯打亮对象
OrbitControls 支持拖拽、缩放、平移
窗口缩放自动适配 ✅
效果与原生写法完全一致,但代码组织更清晰,扩展性更强
当然你可以直接在我分享的stackblitz
中直接尝试更改一些代码,以获得不同的效果。
演示地址:https://stackblitz.com/edit/vitejs-vite-awnvthyl?file=src%2Fcomponents%2FBaseBox.jsx
今天我们在保留原始功能和视觉效果的前提下,体验如何在 React 世界中优雅重建:
DodecahedronGeometry
)准备 3D 模型资源
️ 搭建场景结构骨架
各种准备工作
敬请期待