Load Collada models as a group using Three.js when the page loads

Currently, I am in the process of loading elements of a model and then grouping them together. My goal is to be able to move this group as a whole after all the elements have been loaded.

One challenge I am facing is how to execute code only once all the models have finished loading. I am unsure how to effectively use the .onload function with the colladaLoader and its callback functions. Additionally, I'm not sure if it's wise to use a self-executing function as I have done here. It seems like the best way to loop through a list and load all the models, but is there a better approach?

Below is the code snippet I've been working with. I attempted a workaround by using a counter called "complete," but it doesn't always work reliably. Thank you for any help!

for ( var i=0; i<object.asset.length; i++ ) {

              loader = new THREE.ColladaLoader();
              asset = furniture.asset[i];

    (function(asset) {

                    loader.load(asset["path"], function(collada, materials) {

                        // Function responsible for scaling and positioning the model
                        var mesh = daeAttributes(collada, object, asset, newMaterial);

                        var scene = get_scene();
                        group.add( mesh );
                        complete++;

                        // Once all assets are loaded, add the group to the scene  
                        if (complete===object.asset.length-1) {

                           // Move the group once all models are loaded
                           group = moveModel(group, object);
                           scene.add( group );
                           render();

                        };           
                    });                       
              })(asset);

Update

If there is a list of more than one unique objects to load in, the code works correctly. However, when there is only one object to load, it fails to load that single object.

Answer №1

All the necessary components can be placed within this container for optimal functionality:

<html onload="executeFunction()">

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

Problem Parsing JSON String Containing Backslashes in JavaScript

I recently converted a C# class to a JSON object and then proceeded to stringify the JSON Object. However, during this process, the string was converted with backslashes as escaping characters. Subsequently, when attempting to read the JSON string using th ...

Improving the appearance of a mesh through texture manipulation with ThreeJS and Dat.Gui

I am trying to implement a feature where the texture of my Mesh updates upon clicking a function. Specifically, I want the mesh to dispose of its current texture and replace it with a new one when the 'UpdateMateria' function is clicked. Animat ...

Exploring the retrieval of JavaScript array elements from a ListModel within QML

Currently, I have some JavaScript data that consists of a list of objects containing other objects and arrays, which I want to append to a ListModel. This is what the structure looks like (assuming that the data is generated elsewhere and its structure sh ...

Verify the input fields for errors upon tab press or when moving to a different field and display any errors that may occur

Current tech stack includes ReactJS and TailwindCSS. We have implemented email field validation to show errors as the user types. Here is the code snippet: <div className='flex w-full flex-col space-y-2'> <label htmlFor='ema ...

In search of inspiration to create a recipient list similar to Gmail using Vue3?

Recently, I've been trying to create a recipient list similar to that in Gmail using Vue3 but I'm stuck and unable to find helpful resources online. recipient list I have an array of email addresses that I can loop through and display in a div. ...

Encountered a network error: A rogue token < was found in JSON at position 0 within a new Apollo

https://i.sstatic.net/D25ai.png const httpLink = createHttpLink({ uri: 'http://localhost:3090/' }) const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache() }) client.query({ query: gql` query users { ...

What are the best ways to incorporate mistakes into my JavaScript mortgage calculator?

I am struggling to set up my calculator so that it triggers an error message if the APR goes over 25% or falls below 0. Also, the Loan Term should be greater than 0 and less than or equal to 40, otherwise display an error message. I have attempted differen ...

Is it beneficial to rotate an image before presenting it?

I am looking for a way to display a landscape image in portrait orientation within a 2-panel view without altering the original file. The challenge I am facing is that the image size is set before rotation, causing spacing issues with DOM elements. Is ther ...

What is the best way to simulate the "window.screen.orientation.lock" function with Jest?

Within our hybrid app, we have implemented a cordova plugin to control screen orientation. The AppComponent contains code that manages the screen orientation locking using the window.screen.orientation.lock function. Is there a way to create a mock versi ...

Transform the javascript ES6 class into a functional programming approach

I am interested in converting my reactjs class to a functional programming approach rather than using OOP. Can anyone provide guidance on how to achieve this? Please refer to my code snippet below. import * as h from './hydraulic'; const vertic ...

Issue with breakpoints functionality in MUI v5 and React project

I've been attempting to utilize breakpoints for responsive design on my website, but unfortunately, it doesn't seem to be working correctly. Every time I implement a breakpoint, the entire page goes blank. Below is the code snippet I am working w ...

Basic parallax application, failing to achieve the desired impact

My goal is to create a scrolling effect where the header text moves down slightly, adding some margin on top to keep it in view. I found the perfect example of what I want to achieve with the header text at this website: After spending hours working on i ...

Structuring a Javascript project with a focus on component-based architecture

If I am following a component-based architecture and defining each component as an ES6 module, I organize all components in a /components folder. This folder is further divided into subfolders for grouped components. /js /components - header - ...

Read and manipulate website content using PHP

I recently encountered a challenging situation as a newcomer. Despite searching on Google, I couldn't find any information about it. There is a website that allows users to search for doctors in their area or state. It's possible that the number ...

Unusual Behavior Observed in JavaScript Map Reduce

var t = [-12, 57, 22, 12, -120, -3]; t.map(Math.abs).reduce(function(current, previousResult) { return Math.min(current, previousResult); }); // returns 3 t.map(Math.abs).reduce(Math.min); // returns NaN I'm puzzled as to why the second variant ...

Checking the token's validity using the API within the AuthGuard canActivate method in Angular8

As I navigate through certain routes, I need to validate each refresh request. To achieve this, I am utilizing Angular's AuthGuard. The challenge lies in the canActivate method where I aim to perform validation using an online API. The API endpoint i ...

The data retrieved from the Redis cache does not have pagination implemented

After incorporating Redis cache into my backend API, I encountered an issue where pagination no longer worked on both the backend and frontend. Here is a snippet of the middleware that executes before retrieving all data: const checkCache = (req, res, next ...

Improper menu alignment following a MenuItem hover event within Material-UI

When a MenuItem is hovered over, the position of the Menu container should remain unchanged. [x] The issue persists in the most recent release. However, downgrading MUI to v4.5.0 results in the expected behavior. Current Behavior ...

Is there a built-in way to update a Django template from the server side in response to an event?

As a novice Django developer, my task is to create an auction website. I need to enhance the template that displays item listings and bids, ensuring that the latest bids are updated in real-time without the need for users to refresh the page. While consid ...

Void animations in Angular 2 fail to trigger upon removal

How can I trigger animations when removing a DOM element in Angular2? import { Component, Input, Output, EventEmitter } from '@angular/core'; import { FormGroup, FormControl, Validators } from "@angular/forms"; import { trigger, state, st ...