使用Three JS和React JS加载GLTF模型

时间:2020-02-26 08:35:13

标签: reactjs three.js gltf

我无法使用React JS加载从Sketchfab下载的GLTF文件。当我尝试不使用React(使用常规index.html和index.js)来执行此操作时,它可以工作,但是当我将代码带入React App时,它将在JSON.parse位置0处的JSON中抛出意外令牌<错误。这是我的代码:

import * as THREE from "three";
import {GLTFLoader} from 'three/examples/jsm/loaders/GLTFLoader';


componentDidMount(){


    var scene = new THREE.Scene();
    scene.background = new THREE.Color(0xdddddd);
    var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

    var width = 100;
    var height = 100;
    var intensity = 1.4;
    var rectLight = new THREE.RectAreaLight( 0xffffff, intensity,  width, height );
    rectLight.position.set( 1, 1, 10 );
    rectLight.lookAt( 1, 1, 3 );
    scene.add( rectLight )

    let renderer = new THREE.WebGLRenderer({antialias: true});
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.getElementsByClassName("three-canvas")[0].appendChild( renderer.domElement );


    camera.position.z = 5;
    var animate = function () {
      requestAnimationFrame( animate );
      renderer.render( scene, camera );
    };

    let loader = new GLTFLoader();
    loader.load(
      "../../public/js_models/apple_iphone_xs_max/scene.gltf",
      ( gltf ) => {
          // called when the resource is loaded
        console.log(gltf.scene)
      },
      ( xhr ) => {
        console.log(xhr);
        // called while loading is progressing
        // console.log("The xhr warning isL ",xhr.srcElement.responseText);
    }
      );

    animate();

  }


我了解到它正在呈现我的index.html,这就是它引发错误的原因,但是我真的找不到修复程序,因为我知道GLTF文件在正确的路径中。

如果有任何见解,我将不胜感激。谢谢!

更新

呈现包含gltf文件的组件时的“网络”选项卡 enter image description here

2 个答案:

答案 0 :(得分:2)

所以我确实找到了解决方案!

我没有使用gltf的路径,而是将gltf压缩为glb文件并将其放在我的src文件夹中。然后,我使用导入语法导入了文件:

import filePath from "filepath_of_your_glb_file"

然后,我只需用filePath替换加载程序函数内的加载路径即可!


    let loader = new GLTFLoader();
    loader.load(
      "../../public/js_models/apple_iphone_xs_max/scene.gltf",

如果您想使其动态化(您想刷新多个glb),只需console.log导入的filePath并使用记录的URL作为路径。

答案 1 :(得分:0)

我通过将 3d 模型放在公共文件夹(index.html 和 favicon.ico 所在的位置)并调用来解决这个问题

loader.load("./LittlestTokyo.glb", (gltf) => {
  var obj = gltf.scene.children[0];
  console.log(obj);
});

如果加载器找不到文件,你应该看到“数组没有元素”错误,否则,至少加载器能够找到文件。但是您可能还有其他问题。例如,在我的例子中,由于文件损坏,我有“x 位置的无效字符错误”和“没有 DRACOLoader”可能是由于 .glb 文件格式。