如何在threejs中一般导入gltf模型?

时间:2019-09-05 06:40:45

标签: javascript import three.js model gltf

我需要用三个js创建一个通用的高级查看器,它可以生成Gltf文件。我如何获得有关模型各组成部分的所有信息?

我尝试使用THREE.GLTFLOADER的loader.load()搜索loader类,我找到了信息(在模型组件的scene.children中),但是我无法使其通用。

是否有可以为您提供每个组件的库或函数? 就像函数.getElementById一样,像.GetAllComponents或.GetMaterialsTextures之类的东西(比如我需要获取纹理和模型组件的所有路径)

我不要求你给我我不会学到的答案。

var dracoLoader = new THREE.DRACOLoader();
dracoLoader.setDecoderPath( 'js/draco_decoder.js' );

let loader = new THREE.GLTFLoader(); // I use this as all the video i saw but i you coud explain it (does it help to pack data or just to encode?)
loader.setDRACOLoader( dracoLoader );

loader.load('assets/BM1294_EOS_TABLE_220X280_OUVERT/BM1294.gltf',
function(gltf){
    console.log(gltf);
    let mesh = gltf.scene.children[0]; //one of my model
    renderer.gammaOutput = true;
    renderer.gammaFactor = 2.2;
    scene.add(mesh);
});

谢谢您的帮助:)

1 个答案:

答案 0 :(得分:0)

如果要修改纯JSON,而不使用threejs对象,则可能应该先在GLTFLoader外部加载JSON。例如:

// Load JSON using the native fetch() API.
fetch('model.gltf')
  .then((response) => response.json())
  .then((json) => {
    // View and edit the glTF JSON content.
    console.log(json);
    json.materials[0].baseColorFactor = [1, 0, 0, 1];

    // Parse the modified glTF JSON using THREE.GLTFLoader.
    const jsonString = JSON.stringify(json);
    const loader = new THREE.GLTFLoader();
    loader.parse( jsonString, '', ( gltf ) => {
      // Add the result to the scene.
      scene.add(gltf.scene);
    });
  });
  

注意:这假设您使用的是.gltf扩展名。以.glb结尾的文件是二进制文件,对此答案不包括对其进行解析。您可以使用glTF-Pipeline在两个变体之间轻松转换。

以复杂的方式修改glTF内容将需要对format specification有一定的了解,并且这在堆栈溢出问题的范围之外。您可能会发现,通常可以使用GLTFLoader来加载threejs对象并对其进行修改更容易。