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

相关推荐
万少3 小时前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
橙序员小站5 小时前
Agent Skill 是什么?一文讲透 Agent Skill 的设计与实现
前端·后端
炫饭第一名7 小时前
速通Canvas指北🦮——基础入门篇
前端·javascript·程序员
王晓枫8 小时前
flutter接入三方库运行报错:Error running pod install
前端·flutter
符方昊8 小时前
React 19 对比 React 16 新特性解析
前端·react.js
ssshooter8 小时前
又被 Safari 差异坑了:textContent 拿到的值居然没换行?
前端
曲折8 小时前
Cesium-气象要素PNG色斑图叠加
前端·cesium
Forever7_8 小时前
Electron 淘汰!新的桌面端框架 更强大、更轻量化
前端·vue.js
Angelial8 小时前
Vue3 嵌套路由 KeepAlive:动态缓存与反向配置方案
前端·vue.js
jiayu9 小时前
Angular学习笔记24:Angular 响应式表单 FormArray 与 FormGroup 相互嵌套
前端