Guide to displaying multiple 3D models using the stlloader technique

I am facing an issue with rendering multiple models at the same time. When I try to render them, the display shows up as white and blank with no errors in the console. I am only able to render one model at a time. How can I render multiple models simultaneously? enter image description here

import * as THREE from './threejs/three.module.js';
import {STLLoader} from './threejs/STLLoader.js';
import {OrbitControls} from './threejs/OrbitControls.js';

let scene, camera, renderer, object;

function init(){
    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(
        75,
        window.innerWidth / window.innerHeight,
        0.1,
        10000
    );
    camera.position.z = 10;

    renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);

    scene.add(object);

    let control = new OrbitControls(camera, renderer.domElement);

    let light = new THREE.DirectionalLight(0xffffff);
    light.position.set(0,0,10);
    scene.add(light);

    let light2 = new THREE.DirectionalLight(0xffffff);
    light2.position.set(0,0,-10);
    scene.add(light2);

    animate();
    loadModels();
}

function animate(){
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
}

var models = [];

function loadModels(){
    loadModel('/左肾占位/NING_XUAN_QING_M_056Y_Violet_001.stl', -5);
    loadModel('/左肾占位/NINGXUANQINGM056Y_Turquoise_001.stl', 0);
}

function loadModel(path, positionY){
    let loader = new STLLoader();
    loader.load(path, (model)=>{
        let obj = new THREE.Mesh(
            model,
            new THREE.MeshLambertMaterial({color: 0x00ff00})
        );
        obj.scale.set(0.2, 0.2, 0.2);
        obj.position.set(0, positionY, 0);
        obj.rotation.x = -Math.PI/2;
        models.push(obj);
        scene.add(obj);
    });
}

The model is a Left renal mass comprised of multiple parts, each with its own 3D model file. I need to combine all these parts together to form a complete model.

Answer №1

Let's break down the process of your code in a simpler form:

function start() {
  action1();
}

function action1() {
  start();
}

First of all, the function start() is never triggered. Even if it was, it would lead to an endless loop, like this:

start > action > start > action > and so on...

Moreover, you are not incorporating the loaded items into your scene, resulting in nothing to display. Here is a guideline in pseudocode to ensure a sequential execution and avoid repetition:

// Declare scene and loader variables
let scene, loader;

function start() {
    // Initialize scene and loader
    scene = new THREE.Scene();
    loader = new STLLoader();

    // ...

    action1();
    animate();
}

function action1() {
    // Utilize the loader to import geometry
    loader.load("Violet_001.stl", (model)=>{
        // Upon loading geometry, create a mesh
        let object1 = new THREE.Mesh(
            model,
            new THREE.MeshLambertMaterial({color: 0x00ff00})
        );
        object1.scale.set(0.2, 0.2, 0.2);

        // Add the Mesh to the scene for rendering
        scene.add(object1);
    });
}

function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
}

// Lastly, remember to kick start the process by calling init!
start();

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

Concealing div containers and eliminating gaps

Looking for a way to filter div boxes using navigation? Check this out: <ul> <li><a href="javascript:void(0);" data-target="apples">Appels</a></li> <li><a href="javascript:void(0);" data-target="bananas">Ban ...

Troubleshooting the issue of browser prefix injections not functioning properly in Vue when using the

I've spent an entire afternoon on this issue and I'm completely stuck. After realizing that IE11 doesn't support grid-template, I learned that I need to use -ms-grid-columns and -ms-grid-rows instead. I am attempting to generate CSS and inje ...

Determine if an HTML element contains a specific class using JavaScript

Is there a simple method to determine if an HTML element possesses a particular class? For instance: var item = document.getElementById('something'); if (item.classList.contains('car')) Remember, an element can have more than one clas ...

Understanding the specific types of subclasses derived from an abstract generic class in Typescript

There is a Base generic class: abstract class BaseClass<T> { abstract itemArray: Array<T>; static getName(): string { throw new Error(`BaseClass - 'getName' was not overridden!`); } internalLogic() {} } and its inherito ...

Getting an out-of-range exception (System.ArgumentOutOfRangeException) in C# Razor pages while attempting an AJAX call

I have a razor page model that contains a get-method. public IActionResult OnGetDuration([FromBody]int id) { Subject subject = _service.GetSubjectById(id); int duration = subject.LessonsPerWeek; return new JsonResult('a&apo ...

What is the best way to implement custom serialization for Date types in JSON.stringify()?

class MyClass { myString: string; myDate: Date; } function foo() { const myClassArray: MyClass[] = .... return JSON.stringify(myClassArray); // or expressApp.status(200).json(myClassArray); } foo will generate a JSON string with the date format o ...

HTML: Mark the chosen hyperlink or tag

In my HTML page, I am looking to keep the link selected when it is clicked on. Here is the initial HTML code: <table class="main-dev"> <tr> <td> <a class='titleForm' style="cursor:pointer"> ...

Elevate with Ease: Tailwind's Height Transition

I've been attempting to implement a transition effect using TailwindCSS, but I haven't found an updated version with the latest features. Here's the code snippet: <div id="fadeInElement" className={visible ? " w-2/3 px-5 t ...

remove MongoDB entry using unique identifier

I am currently working on a blog project using nodejs, express, and mongodb. My goal is to delete a specific document by its ID. For instance, if I want to remove a blog post with the ID 52976b1b0855c7e81a6192e9, I would make a request to localhost:3000/bl ...

What is the best way to create a function that shifts a musical note up or down by one semitone?

Currently developing a guitar tuning tool and facing some hurdles. Striving to create a function that can take a musical note, an octave, and a direction (up or down), then produce a transposed note by a half step based on the traditional piano layout (i. ...

Tips for styling buttons in react-admin with custom CSS

I need some help with customizing buttons in react-admin. I am new to the platform and unsure about how to go about changing the button CSS for various actions such as create, edit, and export. Can anyone provide guidance on the best way to customize these ...

Add a new value to the translation token using ng-bind

I'm attempting to loop through an element 5 times using ng-repeat and track by $index. Following that, I aim to utilize the value from $index to supplement a translation token. This appended index value corresponds with the token which retrieves the a ...

Invoking servlet using Ajax

I have created a JSP file with Javascript functions and AJAX calls to invoke a servlet (ReadprojectInfo). <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE ...

Console displays null as the attribute value

When I check the console, I notice that the data-postid attribute is displaying 'null'. What could be causing this issue? I would like to view the data-id in the console when clicking on the button with the id modal-save. I have reviewed my cod ...

Associate text with a color from a predetermined list (JavaScript)

As I work on adding tags to my website for blog posts, I have a specific vision in mind. Each tag should be assigned a unique background color selected from a predefined array of theme colors. My goal is to assign the same background color to tags with id ...

Using the Loop Function in Node.js with EJS Templates

Seeking help with a node.js application that utilizes bootstrap. I am trying to display the bootstrap cards in rows of 3, with each row containing data from my dataset in columns. However, my current implementation using two for loops is leading to repeate ...

Unlocking Controller Functions in AngularJS Directives: A Step-by-Step Guide

Here is a sample controller and directive code: class DashboardCtrl { constructor ($scope, $stateParams) { "ngInject"; this.$scope = $scope; this.title = 'Dashboard'; } loadCharts () { // some logic here } } export def ...

Jssor's dynamic slider brings a touch of sophistication to preview upcoming images

Incorporating the jssor nearby slider to create a nearly fullscreen display. The goal is to set the opacity of upcoming images to 0.25 when they are not in the main viewport, giving the edges of the upcoming and previous slides a slight transparency. < ...

Is it possible to use JavaScript to make a CSS animation mimic the behavior of a :hover effect?

My CSS animation looks like this: HTML: <div class="container" id="cont"> <div class="box show"></div> </div> CSS: .container { width: 100vw; height: 100vh; } .box { position: absolute ...

javascript popup appears twice in IE when using PHP

After testing this script on multiple browsers, an issue arises when using IE. In all other browsers, the form submission alert only appears once. However, in Internet Explorer, the alert pops up twice. What could be causing this discrepancy? <!DOCTYP ...