A guide on extracting the geometry from an STL model imported into three.js

After using STLLoader to load an STL file into three.js, I am trying to access the vertices and geometry of the model for further use. However, I am encountering difficulty in retrieving the geometry after calling the loader. How can I achieve this? Below is the snippet of my code:

var loader = new THREE.STLLoader();
var myModel = new THREE.Object3D();

loader.load("myModel.stl", function (geometry) {
        var mat = new THREE.MeshLambertMaterial({color: 0x7777ff});
        var geo = new THREE.Geometry().fromBufferGeometry(geometry);
        myModel = new THREE.Mesh(geo, mat);
        scene.add(myModel);
 });

console.log(myModel.geometry.vertices)

Answer №1

From the release of three.js R125 onwards, the recommended approach for achieving this task is by using the loadAsync method, which is now integrated into three.js:

This method now returns a promise. You can then utilize a 'then' function to retrieve the geometry of the STL file and create the mesh. While you could also opt for a traditional callback or an async/await structure, the example provided below utilizing the native three.js method presents the simplest solution. The example demonstrates how you can assign the geometry to a global variable once the promise is fulfilled and the STL file is successfully loaded:

// 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(handleFailure);

function handleFailure(){
  console.log('Failed to load the STL file!');
}

function buildScene() {
  console.log('STL file has been loaded, proceeding to build the scene');
  // The bounding box of the STL mesh is now accessible
  console.log(bbox);
  // Continue building your scene...
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adding a component dynamically with a link click in Angular: A step-by-step guide

I am encountering an issue with my web application setup. I have a navigation bar, a home page with left and right divs, and a view-associates component. My goal is to dynamically add the view-associates component into the home's right div when a spec ...

Having trouble simulating a custom Axios Class in JavaScript/TypeScript

Here are the function snippets that I need to test using jest, but they require mocking axios. My attempt at doing this is shown below: // TODO - mock axios class instance for skipped Test suites describe("dateFilters()", () => { beforeEac ...

Struggling with jQuery and the "hash" functionality?

I am encountering issues with jQTouch. The problem arises when I try to use this link: <a href="#site_map" class="swap">Map</a> and initialize jQTouch like this: var jQT = new $.jQTouch({ icon: 'jqtouch.png', ...

Executing Controller Actions within a JavaScript Timer

Presenting my latest timer: var eventDate = new Date(Date.parse(new Date) + 3600); function countdown() { var elapsed = Date.parse(eventDate) - Date.parse(new Date()); var seconds = Math.floor((elaps ...

Timeout error occurred in Async.js because the callback was already triggered

Whenever I execute index.js, I encounter an ETIMEDOUT or ECONNRESET error followed by a Callback was already called error. Initially, my assumption was that the issue stemmed from not including a return before calling the onEachLimitItem callback. Consequ ...

After updating to the latest npm version, the NodeJS server continues to display the error message "Upgrade Required" when loading pages

After developing a Node project using NodeJS version 5.4.x and NPM version 3.3.12 on Windows, I encountered an issue where the project throws an "Upgrade Required" message (HTTP Error code - 426) upon loading the page after some time of inactivity. To add ...

Making changes to a JSON file using JavaScript

Hello everyone, I am a beginner in Javascript and have successfully created a system that allows me to search and filter users in my data.json file. However, I am now looking to develop an application that can add users to the data.json file. Any advice or ...

Issues with making cross-domain requests using jQuery and PHP

I have stumbled upon a similar question that has been asked before, but unfortunately, the answer provided did not give me enough guidance to identify where my code is incorrect. I apologize if this question resembles a previously existing one; I have spen ...

The use of a script redirect in PHP can result in a recursive

Hey there, I'm a new rank newbie here! So I have this code that's supposed to redirect users to the relevant page on both mobile and desktop. But it seems like it's causing a never-ending loop with the webpage constantly reloading. Should I ...

I am having trouble locating my TypeScript package that was downloaded from the NPM registry. It seems to be showing as "module not found"

Having some challenges with packaging my TypeScript project that is available on the npm registry. As a newcomer to module packaging for others, it's possible I've made an error somewhere. The following sections in the package.json appear to be ...

Is it possible to reset the existing localStorage value if we access the same URL on a separate window?

In my app, there are two different user roles: admin and super admin. I am looking to create a new window with a Signup link specifically for registering admins from the super admin dashboard. Is it possible to achieve this functionality in that way? Cu ...

I possess a webpage containing a div element that is loaded dynamically through ajax

One issue I'm facing is with a page containing a div that gets loaded via ajax when a button is clicked. The problem arises when a user tries to refresh the page by pressing F5, as the content of the div gets lost! Is there a way to ensure that when ...

What is the best way to navigate a carousel containing images or divs using arrow keys while maintaining focus?

Recently, I have been exploring the Ant Carousel component which can be found at https://ant.design/components/carousel/. The Carousel is enclosed within a Modal and contains multiple child div elements. Initially, the arrow keys for navigation do not work ...

Utilize the HTTP.get function to serve files in the img src attribute

I am facing an issue where my file can only be accessed if I include an x-authentication token in the header of the "GET" http request. Unfortunately, using a cookie is not an option in this case. This means I cannot simply call for the file by its URL in ...

What is the process of including a pre-existing product as nested attributes in Rails invoices?

I've been researching nested attributes in Rails, and I came across a gem called cocoon that seems to meet my needs for distributing forms with nested attributes. It provides all the necessary implementation so far. However, I want to explore adding e ...

Implementing fullCalendar's addEventSource function with the color customization feature

One feature of my application involves dynamically adding events to the calendar. function AddEventSourceDetailed(act_id) { $('#calendar').fullCalendar('addEventSource', function (start, end, callback) { var startTime = Mat ...

Getting a null value for active user after completing the sign-in process

I am using local storage to store username and password. However, I am encountering an issue where the active user is returning null after a certain line of code, and I am unsure why. console.log("I am the Active user: " + activeUser); const me ...

The React Modal component seems to be malfunctioning within the context of Nextjs

Out of the blue, this issue popped up and I'm puzzled about why it's happening. I have two modals (with different names) that are identical in structure but only one is functioning properly. Both modals use the React-Modal library. The first moda ...

Debouncing in AngularJS with $watch

In my code, I have an HTML search field represented by the following: <input ng-model-options="{ debounce: 500 }" type="text" ng-model="name"> Along with the JavaScript snippet: $scope.$watch('name', function(newVal, oldVal) { ...

Map does not provide zero padding for strings, whereas forEach does

Currently working on developing crypto tools, I encountered an issue while attempting to utilize the map function to reduce characters into a string. Strangely enough, one function works perfectly fine, while the other fails to 0 pad the string. What could ...