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

React-Three.js中GLTFLoader加载本地模型报JSON.parse错误求助

解决GLTFLoader加载本地GLTF模型时的JSON.parse错误

针对你遇到的本地加载模型报JSON.parse: unexpected character错误、远程加载正常的问题,可按以下步骤排查解决:

  • 确认文件路径配置:在React项目中,静态资源需放在public目录下,加载时使用绝对路径(如/scene.gltf)而非相对路径./scene.gltf,避免开发服务器无法正确定位文件。
  • 检查网络请求响应:打开浏览器开发者工具的Network面板,查看scene.gltf的请求结果。如果返回的是HTML页面(如404错误页),说明路径配置错误,需调整文件位置或路径写法。
  • 使用React资源导入规范:若模型放在src目录下,通过import语句导入文件路径,让React自动处理资源URL:
    import modelUrl from './scene.gltf';
    // 加载时使用导入的路径
    loader.load(modelUrl, (data) => { /* 成功回调 */ });
    
  • 排查文件编码问题:确保本地GLTF文件以UTF-8无BOM编码保存。部分编辑器保存时会添加字节顺序标记(BOM),导致JSON解析失败,可使用VS Code等编辑器重新保存并选择"UTF-8"编码。
  • 添加错误回调定位问题:在loader.load中加入错误处理函数,精准捕获加载异常:
    loader.load(
      "/scene.gltf",
      (data) => {
        const object = data.scene;
        object.position.set(0, 0, 0);
        scene.add(object);
      },
      undefined,
      (error) => { console.error('模型加载失败:', error); }
    );
    

修正后的完整示例代码(包含基础场景初始化):

import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';

async function run() {
  // 初始化基础场景
  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  const controls = new OrbitControls(camera, renderer.domElement);
  camera.position.z = 5;

  const loader = new GLTFLoader();
  // 加载public目录下的模型文件
  loader.load(
    "/scene.gltf",
    (data) => {
      const object = data.scene;
      object.position.set(0, 0, 0);
      scene.add(object);
    },
    undefined,
    (error) => { console.error('加载失败:', error); }
  );

  // 渲染循环
  function animate() {
    requestAnimationFrame(animate);
    controls.update();
    renderer.render(scene, camera);
  }
  animate();
}

run();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:27:30