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

Three.js GLTFLoader无法正确读取.glb文件的问题求助

问题描述

我做了一个基于Three.js初始化场景的简单React应用,使用GLTFLoader加载模型时出现以下错误:

GLTFLoader.js:192 SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
at JSON.parse (<anonymous>)
at GLTFLoader.parse (GLTFLoader.js:317:1)
at Object.onLoad (GLTFLoader.js:212:1)
at three.module.js:40464:1

我已在App.js组件顶部导入GLTFLoader:

import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';

并在App函数组件中编写了如下代码:

useEffect(() =>{
    const test = new SceneInit('myCanvas');
    test.initialize();
    test.animate();

    // 加载模型
    const glftLoader = new GLTFLoader();
    glftLoader.load('./football.glb', (gltfscene) => {
      test.scene.add(gltfscene.scene);
    })

  }, []);

我确认.glb模型的文件路径正确,但GLTFLoader仍无法读取文件内容,修改路径后错误依旧。SceneInit类可正常创建基础Three.js场景并显示普通球体,文件夹目录为src目录下包含App.js、football.glb及其他文件。

解决方案

这个错误的核心是GLTFLoader请求到的不是模型文件,而是HTML页面(大概率是404页面),所以才会触发JSON解析报错。以下是几个直接有效的修复步骤:

  • 将模型移至public目录
    React项目中src目录下的文件会被webpack编译处理,直接用相对路径加载静态资源容易出现路径解析问题。把football.glb移到项目根目录的public文件夹中,然后修改加载路径:

    glftLoader.load('/football.glb', (gltfscene) => {
      test.scene.add(gltfscene.scene);
    })
    

    注意路径开头的/,表示从public根目录开始查找文件。

  • 通过import导入模型文件
    若不想移动文件位置,可在App.js中先导入模型资源:

    import footballModel from './football.glb';
    

    加载时直接使用导入的变量:

    glftLoader.load(footballModel, (gltfscene) => {
      test.scene.add(gltfscene.scene);
    })
    

    这种方式webpack会自动处理资源路径,避免手动写路径出现错误。

  • 添加错误回调排查问题
    在load方法中加入错误回调,查看具体请求报错信息,方便精准定位:

    glftLoader.load(
      './football.glb',
      (gltfscene) => { test.scene.add(gltfscene.scene); },
      (xhr) => { console.log((xhr.loaded / xhr.total * 100) + '% loaded'); },
      (error) => { console.error('模型加载错误:', error); }
    )
    
  • 检查webpack自定义配置(如有)
    如果你手动配置过webpack,需确保添加了.glb文件的处理规则,比如用file-loader:

    module.exports = {
      module: {
        rules: [
          {
            test: /\.(glb|gltf)$/,
            use: [
              {
                loader: 'file-loader',
                options: {
                  outputPath: 'models/'
                }
              }
            ]
          }
        ]
      }
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 03:01:03