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

相关推荐
muddjsv2 分钟前
CSS 值的完整计算过程:指定值、计算值、使用值、实际值与动态依赖
前端·css
恋猫de小郭3 分钟前
KotlinLLM 开源 ,一个可以在运行时自己生成永久 Kotlin 代码的 Agent 库
android·前端·人工智能
名字还没想好☜6 分钟前
React createPortal 实战:模态框逃出 overflow:hidden、事件冒泡与焦点管理
前端·javascript·react.js·ecmascript·react·createportal
用户0595401744620 分钟前
Playwright测试AI记忆存储踩坑实录:这个时序问题让我排查了6小时
前端·css
IT_陈寒22 分钟前
Redis踩了个大坑,原来DEL命令也会卡住整个实例
前端·人工智能·后端
一个水瓶座程序猿.40 分钟前
基于Spring AI RAG 的AI知识库前端交互实现
前端·人工智能·spring
breeze jiang1 小时前
React + TypeScript 编辑表单:为什么要区分 name 和 editingName
前端·typescript
米码收割机1 小时前
【移动】线上购物移动端网站(源码+文档)【独一无二】
java·开发语言·前端·python·django
To_OC1 小时前
对接大模型流式接口,我被一个 ReadableStream 卡了半小时
前端·node.js·llm
石小石Orz11 小时前
我发现了开发者AI产品营收的新方向
前端·虚拟现实