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

1,281 阅读1分钟

image.png

搭建项目环境

npm create vite@latest my-vite-app
cd my-vite-app
npm install
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…

image.png

image.png

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

npx gltfjsx scene.gltf --transform

image.png

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

image.png

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

//....
import scenePath from "./scene-transformed.glb";

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

  return (
    // ....
  );
}

useGLTF.preload(scenePath);

Home.jsx

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;

image.png

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

image.png

image.png

来点动画效果

在 useEffect hook 中执行动画

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

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

  return (
    //...
  );
}

Oct-12-2023 22-09-10.gif

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

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