three.js + react 搭建万圣节孤岛🎃

搭建项目环境

bash 复制代码
npm create vite@latest my-vite-app
bash 复制代码
cd my-vite-app
bash 复制代码
npm install
bash 复制代码
npm run dev

安装 three

参考版本:

"@react-three/drei": "^9.88.0"

"@react-three/fiber": "^8.14.5"

"gltfjsx": "^6.2.13",

"react": "^18.2.0"

"three": "^0.157.0"


这个模型嘛,当然是用免费滴: sketchfab.com/3d-models

我们该如何使用这个模型呢

举例:sketchfab.com/3d-models/h...

解压之后,移动到 src/assets 目录下,终端目录定位到该目录下,执行

bash 复制代码
npx gltfjsx scene.gltf --transform

顺利的话,就会得到以下的目录

打开 Scene.jsx 文件,对 scene-transformed.glb 路径进行替换

js 复制代码
//....
import scenePath from "./scene-transformed.glb";

export function Lantern(props) {
  const { nodes, materials } = useGLTF(scenePath);

  return (
    // ....
  );
}

useGLTF.preload(scenePath);

Home.jsx

js 复制代码
import { Canvas } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";
import { Lantern } from "../../assets/halloween_lantern/Scene";
import "./Halloween.css";

const Halloween = () => {
  return (
    <div className="halloween-container">
      <Canvas
        camera={{
          fov: 90,
        }}
      >
        <ambientLight intensity={1} />
        <pointLight color={"orange"} intensity={1} position={[2, 3, 4]} />
        <OrbitControls />
        <Lantern position={[0, 0.3, 0]} scale={[0.8, 0.8, 0.8]} />
      </Canvas>
    </div>
  );
};

export default Halloween;

加载第二个模型,按照上面的步骤

来点动画效果

在 useEffect hook 中执行动画

js 复制代码
export function Fire(props) {
  const group = useRef();
  const { nodes, materials, animations } = useGLTF(scenePath);
  const { actions } = useAnimations(animations, group);

  useEffect(() => {
    actions.Animation.play()
  }, [actions]);

  return (
    //...
  );
}

完整代码:gitee.com/suiboyu/thr...

路由切换到 http://localhost:5173/halloween

相关推荐
用户298698530141 分钟前
React 中 Word 文档转图片的实践方案
前端·javascript·react.js
Csvn2 分钟前
异步并发控制:手写并发池、竞态防护与取消的完整方案
前端·javascript
专业抄代码选手10 分钟前
06|双缓冲与 Commit:让 Fiber 支持第二次渲染
前端·javascript·react.js
涛涛ing10 分钟前
4.8K Star!一套规则让 AI 帮你写出“像人写的”前端代码
前端
万物智能13 分钟前
OpenHarmony源码树解剖—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
前端·后端
天才熊猫君16 分钟前
通用虚拟滚动表格行拖拽排序:从思路到完整实现
前端·javascript
hh95018 分钟前
Agent Plan × DeepSeek Harness:角色 Prompt 驱动的 Agent 分工优化与协作质量实验
java·前端·人工智能·prompt·adg·agent plan·adg成都社区
xiaominlaopodaren19 分钟前
three.js最小地图运行时(九):TileKey 线框与 cursor 坐标探针
javascript·gis·three.js
专业抄代码选手21 分钟前
05|把递归渲染拆成 Fiber:让一棵大树可以暂停
前端·javascript·react.js
像我这样帅的人丶你还24 分钟前
🚀苹果的液态玻璃咋做?🚀
前端·webgl·three.js