使用glb作为react的3D组件

发布于:2025-03-28 ⋅ 阅读:(30) ⋅ 点赞:(0)

使用 gltfjsx 可以把 .glb 模型转换为 React 组件,这样你可以直接在代码中修改 3D 模型的结构、材质等。


🛠️ 步骤 1:安装 gltfjsx

首先,在项目的根目录运行以下命令:

npx gltfjsx model.glb

这个命令会:

  • 解析 model.glb
  • 生成一个 Model.js 文件(默认在当前目录)
  • Model.js 里包含 React 组件,可以直接在 @react-three/fiber 中使用

如果你想指定输出目录:

npx gltfjsx model.glb -o src/components/

🎨 步骤 2:使用生成的 Model.js

转换完成后,你会得到一个 React 组件,比如:

import React, { useRef } from "react";
import { useGLTF } from "@react-three/drei";

export default function Model(props) {
    const { nodes, materials } = useGLTF("/model.glb");
    return (
        <group {...props} dispose={null}>
            <mesh geometry={nodes.Object_0.geometry} material={materials.Material_0} />
        </group>
    );
}

🖼️ 步骤 3:在 Canvas 里使用 Model

import { Canvas } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";
import Model from "./Model";

function App() {
    return (
        <Canvas camera={{ position: [0, 2, 5] }}>
            <ambientLight intensity={0.5} />
            <directionalLight position={[2, 2, 2]} intensity={1} />
            <Model scale={1} />
            <OrbitControls />
        </Canvas>
    );
}

export default App;

🎨 额外优化

1️⃣ 修改颜色、材质

Model.js 里,你可以更改材质:

<mesh geometry={nodes.Object_0.geometry}>
    <meshStandardMaterial color="red" />
</mesh>

2️⃣ 增加动画

import { useFrame } from "@react-three/fiber";

function Model(props) {
    const { nodes, materials } = useGLTF("/model.glb");
    const ref = useRef();

    useFrame(() => {
        ref.current.rotation.y += 0.01; // 让模型旋转
    });

    return (
        <group ref={ref} {...props} dispose={null}>
            <mesh geometry={nodes.Object_0.geometry} material={materials.Material_0} />
        </group>
    );
}



使用 useGLTF 直接加载 .glb

安装必要的依赖

如果你还没有安装 @react-three/fiber@react-three/drei,请先安装:

npm install three @react-three/fiber @react-three/drei

创建 3D 组件

import { useGLTF } from "@react-three/drei";

function Model(props) {
    const { scene } = useGLTF("/model.glb"); // 你的 GLB 文件路径

    return <primitive object={scene} {...props} />;
}

export default Model;

App.js 里使用

import { Canvas } from "@react-three/fiber";
import { OrbitControls } from "@react-three/drei";
import Model from "./Model";

function App() {
    return (
        <Canvas camera={{ position: [0, 2, 5] }}>
            <ambientLight intensity={0.5} />
            <directionalLight position={[2, 2, 2]} intensity={1} />
            <Model scale={1} />
            <OrbitControls />
        </Canvas>
    );
}

export default App;

✅ 优势:

  • 直接加载 .glb 文件,无需手动转换。
  • @react-three/drei 提供的 useGLTF 可以解析 GLB 文件,并返回 scenenodesmaterials 等信息。