Best practice for updating textures in THREE.JS

In my project, I have a set of checkbox booleans that trigger the loading of different textures onto a sphere using three.js.

However, I am facing an issue where these images are not loading quickly enough, causing a performance lag. I believe I need to preload them, but I'm unsure of the best approach to do so. I have also included my current code below, in case there is a more efficient solution or unnecessary code present.

function showPoliticalMap(){
    var world = scene.getObjectByName("world").children[1],
        cloud = scene.getObjectByName("cloud"),
        uri = world.material.map.image.baseURI;

    scene.remove(cloud);
    spotlight.intensity = 0;
    ambientLight.intensity = 1;
    world.material.map.image.currentSrc = uri + "img/earthmapoutlineblue_optimized.jpg";
    world.material.map.image.src = uri + "img/earthmapoutlineblue_optimized.jpg";
    world.material.map.needsUpdate = true;
    world.material.needsUpdate = true;
}

Answer №1

If you are looking to eliminate clouds and adjust light intensity after modifying the texture, it is important to load the texture beforehand. To accomplish this, utilize the TextureLoader, as detailed in the documentation. While the download progress callback may not be necessary in the provided example, retaining the error callback could prove beneficial.

function showPoliticalMap(){
    var world = scene.getObjectByName("world").children[1],
        cloud = scene.getObjectByName("cloud"),
        uri = world.material.map.image.baseURI;

    // create a new loader
    var loader = new THREE.TextureLoader();

    // load the resource
    loader.load(
        // resource URL
        uri + "img/earthmapoutlineblue_optimized.jpg",
        // Function when resource is loaded
        function ( texture ) {
            // manipulate the texture
            world.material.map = texture;
            world.material.needsUpdate = true;

            scene.remove(cloud);
            spotlight.intensity = 0;
            ambientLight.intensity = 1;
        },
        // Function called when download progresses
        function ( xhr ) {
            console.log( (xhr.loaded / xhr.total * 100) + '% loaded' );
        },
        // Function called when download errors
        function ( xhr ) {
            console.log( 'An error occurred' );
        }
    );
}

This code has not been tested yet, so its functionality remains uncertain. Nonetheless, it illustrates the underlying concept effectively.

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

Ordering request parameters in OAuth2 URL with npm passport can be achieved by following a specific method

I have successfully utilized Oauth2 strategies like Github and Twitter to log in to a web application using npm passport. Now, I am interested in logging in using the new global id authentication. You can explore it here ; it's really amazing. Whil ...

Send the response from Facebook to the flash callback on the external interface

I attempted to transfer the response from a Facebook API request obtained through the FB JS-SDK to my flash application using external interface. However, I am having trouble identifying the type of response as it displays [object object] when printed in t ...

"Tips for properly sending a JavaScript variable through an AJAX call to a Django URL

<script> $(document).ready(function () { $(window).on('beforeunload', function () { $.ajax({ // type: 'GET', url: "{% url 'size_reducer:data_de ...

Text that appears as an HTML button is displayed after being compiled using the $

I am attempting to generate a pop up dialog with two buttons using JS code in angular. The script below is what I am using to create the buttons... var html = $('<button ng-click = "cancelAlert()" > Cancel</button > <button ng-click="c ...

Encountering issues with JavaScript functionality upon clicking

I'm struggling to get the div element to slide up or down when clicked, but for some reason nothing is happening. I'm currently following a tutorial and have double-checked everything, yet I can't seem to pinpoint the issue. Any assistance i ...

Unable to navigate to the top of the page in React

When I have a React component with a scrollable div, I am attempting to make the div scroll to the bottom after it is mounted: componentDidUpdate() { var scrollNode = ReactDOM.findDOMNode(this.scrollElement); scrollNode.scrollTop = scrollNode.scro ...

Using Underscore.js debouncer for onresize events - managing .on() and .off() alongside Window Widths [Enquire.js]

In the following code snippet, vw (viewport width) font sizing is simulated only when the window width exceeds 375px. When the window width drops below 375px, jQuery disables resize.mymethod. /* This plugin mimics vw (viewport width) */ function Suppo ...

How can I address the issue of having multiple console logs within the

I am facing an issue where my code is logging to the console 3 times upon page load and incrementing its index. I cannot figure out why this is happening despite attempting to make adjustments within a useEffect. My project involves using the typewriter-ef ...

Ways to extract the text from a modifiable div using angularjs

I am currently facing a challenge in extracting content from an editable div. I am having trouble incorporating the Angular template for this task. The part that is posing a difficulty for me is figuring out how to link model data from the HTML template t ...

Is there a way to program my discord bot to track the number of messages in a channel and display it on its status?

Hey, I have a photography server and I want my bot to keep track of the number of photos in the photos channel and display it in its status. I've noticed other bots with dynamic status updates and I find it really cool, but I'm struggling to figu ...

What is the best way to send and configure GET information when the characters in a URI surpass 5,000?

Currently, I am utilizing a Laravel blade template. However, I encountered an error in my code when the size of the textarea item is quite large. I'm in search of a solution to resolve this issue. Hey everyone! Can you guide me on how to successfull ...

Implement a jQuery loop that utilizes the fadeIn effect

Currently, I have a basic jQuery function in place to generate a small image slider: function gridhover() { $(".grid-item .slide-image").each(function(index) { $(this).delay(400*index).fadeIn(300); }); } $( ".grid-item" ).hover(function() ...

*Efficient ways to eliminate the limit parameter from the URL while using express-paginate.*

I am in the process of implementing paging with the express-paginate module. However, I am encountering an issue where the limit parameter is showing up in the URL like this: http://example.com:3010/feeds?page=2&limit=10. My preference is to eliminate ...

Retrieve all entries using Sequelize ORM in a One-To-Many relationship situation

In my database, I have two tables named Users and Shops. Users can own multiple shops, while each shop is owned by only one user. The technology stack I am using includes Node.js with the Sequelize ORM for PostgreSQL databases. Encountered Issue When ret ...

The intersection observer fails to activate upon the initial page load and when navigating back to a

When utilizing useIntersectionObserver from VueUse to trigger a fade-in animation upon an element entering the viewport, I encountered a specific issue. Upon navigating to another page or clicking on an item in the carousel and then returning to the previo ...

The Lenis smooth scrolling feature (GSAP) is not functioning properly

I have encountered an issue with the smooth scrolling feature of gsap causing a delay on my website. This problem is only resolved when I manually go into the browser settings and disable smooth scrolling by navigating to chrome://flags/#smooth-scrolling ...

Efficiently loading images into a navigation flyout: the ultimate guide

I have a large navigation flyout menu that includes images to display the items. Although it is functioning properly, I have noticed that the page load time is a bit slow due to the higher number of images being loaded. Here is an example of my code: &l ...

Having difficulty drawing an arrow connecting one mesh object to the surface of another mesh object

When attempting to draw an arrow from one mesh object to another, I encountered some issues. Directly using the positions of the objects as arguments in the Arrow Helper resulted in the arrow going inside the object due to the position representing the cen ...

Issue with Three.js: GLTF model not positioned correctly at origin point

After attempting to load a glTF model with a 0,0,0 position, I noticed that it appears far from the origin. Upon trying to rotate the glTF model, I observed that it spins around (indicated by blue dots) the origin instead of spinning from its center. Thi ...

jQuery function triggers a URL redirect upon form change

I'm trying to implement a function that will redirect the form to a specific URL when an option is selected. However, even though I can retrieve the correct URL in my JavaScript and it appears correctly in the browser, the content doesn't seem to ...