首页 > 解决方案 > 三 JS xhr Infinity % 已加载

问题描述

我目前正在与 ThreeJS 合作,我承认我是一个新手。我可以在其中创建自己的模型(基本模型),但在加载外部 gltf 文件时遇到问题。我在 React 项目中使用它。

我加载模型的代码如下:

componentDidMount() {
  let scene = new THREE.Scene();
  scene.background = new THREE.Color(0xdddddd);
  let camera = new THREE.PerspectiveCamera(
    45,
    window.innerWidth / window.innerHeight,
    1,
    500
  );
  camera.position.set(1, 1, 20);

  let renderer = new THREE.WebGLRenderer({ alpha: false });
  renderer.setSize(500, 500);
  document.getElementById("three-canvas").appendChild(renderer.domElement);
  // Load Light
  let ambientLight = new THREE.AmbientLight(0xcccccc);
  scene.add(ambientLight);

  let directionalLight = new THREE.DirectionalLight(0xffffff);
  directionalLight.position.set(0, 1, 1).normalize();
  scene.add(directionalLight);

  camera.position.z = 5;
  camera.lookAt(new THREE.Vector3(0, 0, 0));

  let loader = new GLTFLoader();
  loader.load(
    "./assets/scene.gltf",
    (gltf) => {
      scene.add(gltf.scene);
    },
    // called while loading is progressing
    function (xhr) {
      console.log((xhr.loaded / xhr.total) * 100 + "% loaded");
      console.log(xhr.loaded, xhr.total);
      console.log(xhr);
    },
    // called when loading has errors
    function (error) {
      console.log("An error happened", error);
    }
  );
  let animate = function () {
    requestAnimationFrame(animate);
    render();
  };
  function render() {
    renderer.render(scene, camera);
  }
  animate();
}

render() {
  return (
    <div className="App">
        <div id="three-canvas"></div>
    </div>
  );
}

该文件是我的 App.js 文件,位于 src 目录中。

我面临的问题是我的 3d 图像没有在这里加载,而是我得到了附加的截图。它应该是一辆蓝色的3d汽车。

我还在控制台中得到以下信息:

无限%已加载

这对应于代码行:

console.log((xhr.loaded / xhr.total) * 100 + "% loaded");

我也得到:

164814 0

对应于:

console.log(xhr.loaded, xhr.total);

这告诉我总数为 0,但我不确定这意味着什么。

我会注意到,如果我将 gltf 文件切换到公共目录,则会出现一个全新的错误,我会在控制台中看到以下内容:

An error happened SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at GLTFLoader.parse (GLTFLoader.js:214)
    at Object.onLoad (GLTFLoader.js:146)
    at XMLHttpRequest.<anonymous> (three.module.js:36370)

我讨厌成为“嘿,我是新手,帮帮我”类型,因为我使用 javascript 已经有一段时间了,但我对 ThreeJS 还是很陌生,并且迷失了片刻。我一直在研究这个并尝试不同的解决方案大约 2-3 个小时,但无济于事。我浏览了threejs网站上的文档,并通过https://gltf-viewer.donmccurdy.com/验证了文件本身正确加载

有些东西告诉我它是:1)我的灯光可能关闭,因此无法正确显示图片 2)文件未正确加载,因此为 0xhr.total

任何帮助将不胜感激。谢谢!

标签: javascriptreactjsthree.js

解决方案


推荐阅读