You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在react-three-fiber中使用GLTFExporter导出多个不同3D场景

实现方案

1. 资源预处理

将所有需要用到的立方体表面纹理统一存放在项目静态资源目录下,比如public/textures/cube-textures/,提前读取该目录下所有纹理文件的路径,存入数组用于后续遍历,以Vite项目为例可以用批量导入语法快速获取所有路径:

// 批量读取cube-textures目录下所有png格式纹理
const textureFileList = Object.values(import.meta.glob('/public/textures/cube-textures/*.png', { eager: true })).map(item => item.default)

如果是Webpack项目可以用require.context实现相同效果。

2. 核心导出逻辑实现

首先引入GLTFExporter,维护当前导出的纹理索引状态,封装导出逻辑:

import { useRef, useState } from 'react'
import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js'
import * as THREE from 'three'

// 组件内逻辑
const [currentTexIndex, setCurrentTexIndex] = useState(0)
const sceneRef = useRef() // 场景ref,你已提前绑定
const cubeRef = useRef() // 立方体ref,你已提前绑定
const exporter = new GLTFExporter()

const handleExport = () => {
  // 加载当前索引对应的纹理,替换立方体材质
  const textureLoader = new THREE.TextureLoader()
  const currentTexture = textureLoader.load(textureFileList[currentTexIndex])
  currentTexture.needsUpdate = true
  cubeRef.current.material.map = currentTexture
  cubeRef.current.material.needsUpdate = true

  // 纹理加载完成后执行导出
  currentTexture.onLoad = () => {
    exporter.parse(
      sceneRef.current,
      (exportResult) => {
        // 导出为gltf格式
        const blob = new Blob([JSON.stringify(exportResult)], { type: 'application/json' })
        const downloadUrl = URL.createObjectURL(blob)
        const linkDom = document.createElement('a')
        linkDom.href = downloadUrl
        linkDom.download = `立方体_${currentTexIndex}.gltf`
        linkDom.click()
        URL.revokeObjectURL(downloadUrl)

        // 更新索引,判断是否遍历完所有纹理
        if (currentTexIndex < textureFileList.length - 1) {
          setCurrentTexIndex(prev => prev + 1)
          // 若需要一键批量导出所有纹理立方体,取消下一行注释即可
          // handleExport()
        } else {
          alert('所有纹理立方体已导出完毕')
          setCurrentTexIndex(0)
        }
      },
      (error) => console.error('导出失败:', error),
      { 
        binary: false, // 需要导出glb格式时改为true,对应调整blob类型和文件后缀即可
        includeCustomExtensions: true
      }
    )
  }
}

3. 绑定触发按钮

在组件UI部分添加触发按钮,点击即可按顺序导出不同纹理的立方体:

<button onClick={handleExport}>导出下一个纹理立方体</button>

扩展说明

如果需要为不同类型的立方体配置专门的纹理目录,只需要新增不同的纹理路径数组,切换立方体类型时替换textureFileList为对应目录的路径数组即可。


内容的提问来源于stack exchange,提问作者moistCash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 09:36:04