Steps for removing a p5.js instance once three.js assets have finished loading

I am trying to implement a preload animation using a p5 sketch while loading a three.js gltf file onto my webpage. The idea is to have the p5 animation play while the heavy gltf file loads in the background. However, I am facing issues with triggering the boolean trigger when using the loading manager in three.js.

Here's a snippet of code showcasing the interactions:

P5

function playSketch(){
  var sketch = function(p){
      p.setup = function(){
        // Code for setup
      }
      p.draw = function(){
        // Code for animation loop
      }
  }
  var myp5 = new p5(sketch);
}

Three.js, inside the main() function

const manager = new THREE.LoadingManager();
  manager.onStart = function ( url, itemsLoaded, itemsTotal ) {
    console.log( 'Started loading file: ' + url + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
  };
  manager.onLoad = function ( ) {
    console.log( 'Loading complete!');
    loadSketch = true;
  };
  manager.onProgress = function (itemsLoaded, itemsTotal ) {
    console.log( 'Loading file: ' + '.\nLoaded ' + itemsLoaded + ' of ' + itemsTotal + ' files.' );
  };

function setBool(){
  if(loadSketch){
    console.log('this works');
    myp5.remove();
  }
}

main();
playSketch();
setBool();

Unfortunately, the setBool function is not triggered as expected, and the p5 sketch continues running even after the loading is complete. How can I properly remove the p5 instance once the loading process is finished? Any help would be greatly appreciated. Thank you.

Answer №1

There appear to be two separate issues at play here. Firstly, the setBool() function is being called immediately after the main() and playSketch() functions. Since the LoadingManager in three.js may not trigger the onLoad handler right away, the variable loadSketch could still be false when setBool is executed. To address this, one solution could be to have the onLoad function directly call the .remove() function or pass a callback function to the main() method instead of calling setBool right after.

The second issue stems from the scope of the myp5 variable, which is declared within the playSketch() function, making it inaccessible to the setBool() function.

It would greatly assist in providing a precise solution if you were to include a runnable snippet with a minimal reproducible example in your query.

Answer №2

One thing I overlooked was the importance of mentioning:

const gltfLoader = new GLTFLoader(manager);

while setting up my loader (obviously!).

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

Steps for returning a res.send(req.body) upon sending back to a function

I'm currently working on sending the req.body from a POST request route back to the executing function for further processing. The structure of req.body is as follows: { username: 'aa', password: 'ss' } After making the post requ ...

Tips for saving HTML code within a concealed field utilizing jQuery

What is the best way to store a string with HTML tags in a hidden field using jQuery? I am attempting to use this code, but it's not functioning as expected: var terms = $('#TermsAndCondition').val(); alert($('#hdnTerms').val( ...

Creating a JSON data array for Highcharts visualization: rearranging values for xAxis and columns

I am facing an issue with my column chart where JSON data is being parsed in the "normal" form: Years are displayed on the xAxis and values on the yAxis (check out the fiddle here): array( array( "name" => "Bangladesh", ...

Steps to send an object array using a promise

I've put in a lot of effort but haven't found a solution that works well for me. I attempted using promise.all and setting the array globally, but it didn't work out. My goal is to search through three MongoDB collections, match the finds, ...

Countdown timer that counts down in reverse when the browser is minimized

I am currently working on a JavaScript project where I have implemented a countdown timer in seconds. Once the timer hits zero, it triggers a specific function. The timer functions correctly, however, if the browser enters sleep mode or is minimized, the ...

Ways to create a self-contained video viewer

Is it possible to create a self-contained video player similar to jwplayer or the YouTube video player using just HTML, CSS, and JavaScript? I know that I can build a video player by utilizing the video tag along with some custom javascript and css, but ho ...

Tips for delivering a heartfelt message when a user adds an item

import React from 'react'; import { useForm } from "react-hook-form"; import { toast } from 'react-toastify'; const AddStorage = () => { const { register, handleSubmit } = useForm(); const submitData = data => ...

Utilizing AngularJS to calculate elapsed time and continuously update model and view accordingly

Situation Currently, I am interested in developing a web application that tracks a specific data set based on the time since the page was loaded. For example, "how many calories have you burned since opening this webpage?" I am still trying to grasp the ...

Disregard periods in URLs when configuring nginx servers

While developing with Vite in development mode via Docker on my Windows 10 machine, I encountered an issue where the local custom domain would not load due to a required script failing to load. The specific script causing the problem is /node_modules/.vit ...

Display modal after drop-down selection, triggered by API response

Currently, I am working on integrating an API to enable users to make payments through a modal. Users should be able to enter an amount and select a payment frequency. I have successfully extracted various payment frequencies from the API response and pop ...

Alter the style attribute using JavaScript

I have a calendar table row that needs to be displayed or hidden based on the month. HTML: <tr id="bottomrow" class="week" valign="top" style="display:none;"> <td class="day" id="d36"> <div class="daynumb" id="x36">& ...

Ways to populate dynamic choices for multiple Select boxes within an ng-repeat loop

When I click the "Add Row" button on an Html form, dynamic rows are added. Each row contains a 'Country' select and a 'State' select. The issue I am facing is that when I select a country in one row, all other row values change as well. ...

The use of ReactDom.render is no longer permissible in Next.js

I just set up a fresh Next JS application using Next 12. Encountering this issue consistently on every page load in the browser: Alert: The use of ReactDOM.render is no longer supported in React 18. Please switch to createRoot instead. Until you make th ...

Accessing Data from Nested PHP Array in Javascript

My current situation is this: I have a MYSQL database that consists of two fields: 'ID' and 'string'. The 'string' field stores serialized arrays. To extract the data back, I utilize the following PHP code: $result = mysql_q ...

When attempting to push `content[i]` into an array in AngularJS, it is flagged

In my JSON data, I have the following structure: var data = [{ id: 1, name: 'mobile', parentid: 0, limit:3 }, { id: 2, name: 'samsung', parentid: 1 }, { id: 3, name: 'moto', parenti ...

Cloudflare SSL Error 522 Express: Troubleshooting Tips for Res

After setting up my express project using express-generator, I decided to make it work with a cloudflare SSL Certificate for secure browsing over https. My express app is running on port 443. Despite my efforts, when I try to access the domain, I encount ...

Blur images on parent div when hovering using javascript

After some extensive searching, I came across a few helpful explanations on how to achieve my desired outcome. By combining them, I was able to get everything working smoothly with the hover effect over the image itself. However, when I attempted to trigge ...

Is it possible to automatically redirect to a different URL if the server is running slow when clicking?

Is it possible to utilize Javascript, AJAX, or another client-side technology to automatically redirect the user to a different URL if the initial URL is slow to respond when clicked on? For example, if a link redirects to URL1 and there is no response fr ...

Arrange the grid in a pleasing manner

I'm really struggling with this issue. In my current setup, I have a Grid container that holds two separate grids - one for a textfield and another for a checkbox. Unfortunately, I can't seem to get them to align properly. <Grid container& ...

creating a new date instance with a specific time zone

Creating a Date object with a dynamically selected timezone is my current goal while I am located in the IST time zone. To avoid the unpredictable behavior of Date.parse(), I am looking for an alternative method. Let's say we set the tzOffset to +05:3 ...