T01▸3D001▸three
Rotating Cube
旋轉立方體
難度 ★★★★★標籤 three · r3f · basic2 min read
效果簡述
Three.js 的 Hello World。用 @react-three/fiber 在 React 裡寫 3D。
Canvas + mesh + boxGeometry + 燈光 + useFrame 旋轉。
Claude Code Prompt
參考:3D001 rotating cube
技術:@react-three/fiber
具體行為:
- <Canvas camera={{ position: [3,2,3], fov: 50 }} dpr={[1,2]}>
- ambientLight + directionalLight
- mesh > boxGeometry + meshStandardMaterial
- useFrame((_, delta) => ref.current.rotation.y += delta * 0.6)
限制:
- dpr 別給 [1, 3](高 DPI 螢幕會卡)
- 旋轉速度 0.3 ~ 0.8 rad/s 最舒服
- 一頁不要超過 3 個 Canvas(GPU 吃緊)完整程式碼
'use client'
import { Canvas, useFrame } from '@react-three/fiber'
import { useRef } from 'react'
import type { Mesh } from 'three'
function Cube() {
const ref = useRef<Mesh>(null)
useFrame((_, d) => {
if (!ref.current) return
ref.current.rotation.x += d * 0.4
ref.current.rotation.y += d * 0.6
})
return (
<mesh ref={ref}>
<boxGeometry args={[1.6, 1.6, 1.6]} />
<meshStandardMaterial color="#c2410c" />
</mesh>
)
}
export function RotatingCube() {
return (
<Canvas camera={{ position: [3, 2, 3], fov: 50 }} dpr={[1, 2]}>
<ambientLight intensity={0.5} />
<directionalLight position={[5, 5, 5]} intensity={1} />
<Cube />
</Canvas>
)
}何時用
- ✅ 學 Three.js 的起點
- ✅ 產品 3D 預覽(簡易版)
- ✅ Hero 區的小裝飾
何時別用
- ❌ 一頁多個(GPU 喘)
- ❌ 行動裝置主要用戶(電池殺手)
- ❌ 預算少 / 時程趕的專案
我踩過的坑
-
'use client'不能漏:R3F 一定要 client component。 -
沒燈光全黑:StandardMaterial 需要光源,純 ambient 看不到立體感。
-
dpr 太高機器爆炸:[1, 2] 是安全範圍。
相關效果
- T03 Distort Sphere — 進階形變