ThreeJS Loading Page

Just starting out with ThreeJS and currently in the process of building a 3D Configurator. I'm looking to add a loading screen before the obj object loads, here's my current code:

<!DOCTYPE html>

    </style>
</head>
<body>

    <div id="container"></div>


    <script src="js/three.js"></script>
    <script src="js/OrbitControls.js"></script>
    <script src="js/RGBELoader.js"></script>
    <script src="js/HDRCubeTextureLoader.js"></script>

    ... (more script sources)

    <script src="js/OBJLoader.js"></script>


    <script>
        // javascript code here
    </script>

</body>

I attempted something like this:

    var loadingScreen =
        {
            scene = new THREE.Scene();
            camera = new PerspectiveCamera(90, 1280/720, 0.1, 1000);
            box : new THREE.Mesh(
                new THREE.BoxGeometry(0.5,0.5, 0.5),
            new THREE.MeshBasicMaterial ({color:0x4444ff})
        )
        };

        var RESORUCES_LOADED = false;

Added the loadingscreen into function init:

            loadingScreen.box.position.set(0,0,5);
            loadingScreen.camera.lookAt(loadingScreen.box.position);
            loadingScreen.scene.add(loadingScreen.box);

And finally in the animate function:

    if (RESORUCES_LOADED == false)
            {
                requestAnimationFrame(animate);
                renderer.render(loadingScreen.scene, loadingScreen.camera);
                stats.begin();
                render();
                stats.end();

                return;
            }

However, it's not working as expected. Any advice on how to improve this?

Answer №1

Instead of opting for a distinct scene, I suggest utilizing a sleek preloading screen created with CSS. Check out the example I put together in a fiddle that demonstrates a smooth fade-out effect for the loading screen.

The key aspect lies in the onLoad callback function of THREE.LoadingManager:

const loadingManager = new THREE.LoadingManager( () => {

    const loadingScreen = document.getElementById( 'loading-screen' );
    loadingScreen.classList.add( 'fade-out' );
    
    // if needed: remove loader from DOM using event listener
    loadingScreen.addEventListener( 'transitionend', onTransitionEnd );
    
} );

https://jsfiddle.net/gex9km1j/

I took inspiration for the CSS design from this source:

Answer №2

If you fail to eliminate the loader upon onTransitionEnd, a CSS animation will persist within your DOM continually.

With that in mind, here is my approach:

 const loadingManager = new THREE.LoadingManager(() => {
            this.loadingScreenEl.nativeElement.classList.add('fade-out');
            setTimeout(() => {
                this.loadingScreenEl.nativeElement.style.display = 'none';
            }, 1000);
        }, () => {
            this.loadingScreenEl.nativeElement.style.display = 'block';
            if (this.loadingScreenEl.nativeElement.classList.contains('fade-out')) {
                this.loadingScreenEl.nativeElement.classList.remove('fade-out');
            }
        });

Explanation:

1 - Upon loading completion, you fade out the loader and remove it after 1 second.

2 - During progress, display the loader and remove the fade-out class if present.

Environment: Utilizing Angular 10 and Three.js

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

Encountering an Issue: Unable to Generate Line Chart with gRaphael Library

I'm currently working with the gRaphael JavaScript library to create a basic line graph. Here is the code I have implemented on my page: <script language="javascript" type="text/javascript"> var paper = Raphael(10, 50, 640, 480); paper.g.line ...

After completing the installation of "node-pty" in an electron-forge project on Linux, I noticed that the pty.node.js file is not present. What is the proper way to install node-pty

Following the installation of node-pty, an external module utilized to generate pseudo terminals with Node.js in a boilerplate electron-forge project, I encountered an issue. The error indicated that a core module within node-pty was attempting to import a ...

Why is my jQuery clearQueue function malfunctioning?

I'm facing an issue with my AJAX function where multiple notifications are being displayed if the user calls it repeatedly in a short span of time. I want to show the notification only once and avoid queuing them up. AJAX FUNCTION function update(up ...

Using the functionalities of the parent component

Exploring Base.vue <template><div>{{ name }}</div></template> <script> export default { data() { return {name: 'Example Component'}; } }; </script> And introducing Extended.vue: <script> ...

Pass the form data to a Bootstrap modal upon submission of the form

I'm attempting to retrieve form data and convert it to JSON to display in a modal dialog that opens on the Submit button click! This is my progress so far: HTML <form class="form-horizontal" id="configuration-form"> --irrelevant-- <button ...

Tips for incorporating a variable into a JSON object value when dynamically constructing an object

Is there a way to dynamically create an array of objects using a for loop? I have different arrays with values for the key value pairs of these objects. The code snippet I tried is not producing the expected result. var characters = ['Iron Man', ...

React.js Component Composition Problem

I am attempting to replicate the following straightforward HTML code within a React environment: Traditional HTML <div> Hello <div>child</div> <div>child</div> <div>child</div> </div> React(working ...

The request body contains no information

I'm having trouble debugging this issue. Can anyone help me out? When using console.log(req.body), I am getting an empty object {}. I've tried multiple approaches but still can't figure out the problem. Even after attempting to use middle ...

IIFE and the Twitter share button are a powerful duo

As I experiment with this quick creation of mine, two questions have arisen. The first one is, how can I encapsulate all the JS code within an IIFE without breaking it? The second question is about finishing the twitter button to enable sharing the act ...

What could be the reason for my React Component not properly associating with the image?

The title appears to be correctly displayed, but there seems to be an issue with the images. I've thoroughly reviewed the code multiple times, but unfortunately, I'm unable to identify the problem. Please provide guidance on what changes need to ...

express-validator never accepts valid input

Currently, I am working on a project using the most recent version of nodejs and express. The basic site setup is complete, and now I am focusing on implementing user authentication based on what I've learned from this course. However, no matter what ...

In search of a highly efficient webservices tutorial that provides comprehensive instructions, yielding successful outcomes

I've reached a point of extreme frustration where I just want to break things, metaphorically speaking, of course. For the past week, I've been trying to learn how to create a web service using C# (whether it's WCF or ASMX, I don't rea ...

Exploring prototypal inheritance through Angularjs module.service设计(Note: This

Having worked with Angularjs for a few months now, I am curious about implementing efficient OOP within this framework. Currently, I am involved in a project where I need to create instances of a "terminal" class that includes constructor properties and v ...

The Express Validator is unable to send headers to the client once they have already been processed

I recently integrated express-validator in my Express JS project, but encountered a warning when sending invalid fields to my api: UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client This ...

Is the concept of Controlled and Uncontrolled Components in VueJs similar to that of React?

When it comes to React, there is a distinction between controlled and uncontrolled components explained in detail at this link. Controlled components function within the React model where state is managed in the virtual DOM. In contrast, uncontrolled com ...

Accordion in Bootstrap 5.3 behaving independently of data-bs-parent

I am currently working on designing an accordion feature where the headers are displayed in a column on the left side, and when expanded, the content appears in a column on the right side. Everything is working perfectly except for the fact that I have t ...

HTML Scripts: Enhancing Web Functionality

I have another question regarding executing a script (docs()) upon clicking on text. I attempted to use the following code: <p><span class="skill">Documentation can be found here.<script>docs()</script></span></p> Unfo ...

Challenges with Tab navigation in React and Ionic 5

I am facing a challenge with getting the tabs navigation to function correctly. Here is my current code: App.tsx: const App: React.FC = () => <IonApp> <IonReactRouter> <IonRouterOutlet id="main"> < ...

Choose a date range from the date picker

I am currently attempting to combine two dates using a rangepicker. Below is the command used to select the date: Cypress.Commands.add('setDatePickerDate', (selector, date) => { const monthsShort = [ 'janv.', 'févr.& ...

Creating a primary index file as part of the package building process in a node environment

Currently, I have a software package that creates the following directory structure: package_name -- README.md -- package.json ---- /dist ---- /node_modules Unfortunately, this package cannot be used by consumers because it lacks an index.js file in the r ...