加载模型
R3F 中加载模型
加载 GLTF 模型
import { useLoader } from "@react-three/fiber";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
function Scene() {
const gltf = useLoader(GLTFLoader, "/Poimandres.gltf");
return (
<Suspense fallback={null}>
<primitive object={gltf.scene} />
</Suspense>
);
}
也可以加载为 JSX 组件:
/*
Auto-generated by: https://github.com/pmndrs/gltfjsx
*/
import React, { useRef } from "react";
import { useGLTF } from "@react-three/drei";
export default function Model(props) {
const group = useRef();
const { nodes, materials } = useGLTF("/Poimandres.gltf");
return (
<group ref={group} {...props} dispose={null}>
<mesh
castShadow
receiveShadow
geometry={nodes.Curve007_1.geometry}
material={materials["Material.001"]}
/>
<mesh
castShadow
receiveShadow
geometry={nodes.Curve007_2.geometry}
material={materials["Material.002"]}
/>
</group>
);
}
useGLTF.preload("/Poimandres.gltf");
现在我们可以像导入任何 React 组件一样导入我们的模型,并在我们的应用程序中使用它。
import { Suspense } from "react";
import { Canvas } from "@react-three/fiber";
import { Environment } from "@react-three/drei";
import Model from "./Model";
export default function App() {
return (
<div className="App">
<Canvas>
<Suspense fallback={null}>
<Model />
<Environment preset="sunset" background />
</Suspense>
</Canvas>
</div>
);
}
当模型比较大的时候,还可以通过 Loader 来展示进度:
import { Html, useProgress } from "@react-three/drei";
function Loader() {
const { progress } = useProgress();
return <Html center>{progress} % loaded</Html>;
}
export default function App() {
return (
<Canvas>
<Suspense fallback={<Loader />}>
<Model />
</Suspense>
</Canvas>
);
}
加载 OBJ 模型
import { OBJLoader } from "three/examples/jsm/loaders/OBJLoader";
import { useLoader } from "@react-three/fiber";
function Scene() {
const obj = useLoader(OBJLoader, "/Poimandres.obj");
return <primitive object={obj} />;
}
加载 FBX 模型
import { useLoader } from "@react-three/fiber";
import { FBXLoader } from "three/examples/jsm/loaders/FBXLoader";
function Scene() {
const fbx = useLoader(FBXLoader, "/Poimandres.fbx");
return <primitive object={fbx} />;
}