Javascript 如何在three.js中获取从STL导入的模型的几何图形

Javascript 如何在three.js中获取从STL导入的模型的几何图形,javascript,three.js,Javascript,Three.js,我正在使用STL加载程序将STL文件加载到three.js中,我希望在调用加载程序以供进一步使用后获得模型的顶点(和几何体)。我该怎么做?我当前的代码如下,但调用加载程序后无法获取几何体 var loader=new THREE.STLLoader(); var myModel=new THREE.Object3D(); loader.load(“myModel.stl”,函数(几何体){ var mat=new THREE.MeshLambertMaterial({color:0x7777f

我正在使用STL加载程序将STL文件加载到three.js中,我希望在调用加载程序以供进一步使用后获得模型的顶点(和几何体)。我该怎么做?我当前的代码如下,但调用加载程序后无法获取几何体

var loader=new THREE.STLLoader();
var myModel=new THREE.Object3D();
loader.load(“myModel.stl”,函数(几何体){
var mat=new THREE.MeshLambertMaterial({color:0x7777ff});
var geo=new THREE.Geometry().fromBufferGeometry(几何体);
myModel=新的三个网格(geo、mat);
scene.add(myModel);
});

console.log(myModel.geometry.vertices)
从three.js R125开始,建议使用loadAsync方法执行此操作,该方法现在是three.js的本机方法:

该方法返回一个承诺。然后,您可以使用“then”获取STL的几何图形并创建网格。您也可以使用传统的回调或异步/等待结构,但我认为下面使用原生three.js方法的示例是最简单的方法。该示例显示了在解析承诺并加载STL文件后,如何将几何体转换为全局变量:

// Global variables for bounding boxes
let bbox;

const loader = new STLLoader();
const promise = loader.loadAsync('model1.stl');
promise.then(function ( geometry ) {
  const material = new THREE.MeshPhongMaterial();
  const mesh = new THREE.Mesh( geometry, material );
  mesh.geometry.computeBoundingBox();
  bbox = mesh.geometry.boundingBox;
  scene.add( mesh );
  buildScene();
  console.log('STL file loaded!');
}).catch(failureCallback);

function failureCallback(){
  console.log('Could not load STL file!');
}

function buildScene() {
  console.log('STL file is loaded, so now build the scene');
  // !VA bounding box of the STL mesh accessible now
  console.log(bbox);
  // Build the rest of your scene...
}

从three.js R125开始,建议使用loadAsync方法来实现这一点,该方法现在是three.js的本机方法:

该方法返回一个承诺。然后,您可以使用“then”获取STL的几何图形并创建网格。您也可以使用传统的回调或异步/等待结构,但我认为下面使用原生three.js方法的示例是最简单的方法。该示例显示了在解析承诺并加载STL文件后,如何将几何体转换为全局变量:

// Global variables for bounding boxes
let bbox;

const loader = new STLLoader();
const promise = loader.loadAsync('model1.stl');
promise.then(function ( geometry ) {
  const material = new THREE.MeshPhongMaterial();
  const mesh = new THREE.Mesh( geometry, material );
  mesh.geometry.computeBoundingBox();
  bbox = mesh.geometry.boundingBox;
  scene.add( mesh );
  buildScene();
  console.log('STL file loaded!');
}).catch(failureCallback);

function failureCallback(){
  console.log('Could not load STL file!');
}

function buildScene() {
  console.log('STL file is loaded, so now build the scene');
  // !VA bounding box of the STL mesh accessible now
  console.log(bbox);
  // Build the rest of your scene...
}

在回调函数的末尾调用console.log(myModel.geometry.vertices)。加载是非同步的,因此您尝试在对象尚未下载时访问属性。非常感谢,下载模型后是否有访问属性的方法?您可以在回调函数中执行此操作。或者,一般来说,首先加载您需要的所有资源,然后使用它们进行处理。在回调函数末尾调用
console.log(myModel.geometry.vertices)
。加载是非同步的,因此您尝试在对象尚未下载时访问属性。非常感谢,下载模型后是否有访问属性的方法?您可以在回调函数中执行此操作。或者,一般来说,首先加载您需要的所有资源,然后使用它们来完成任务。