Loading textures for cubes using Three.js TextureLoader and CubeGeometry

I am currently learning threejs and I am trying to apply 6 different textures to each side of a cube. I initially achieved this using loadTexture.

var material3 = new THREE.MeshPhongMaterial( {map: THREE.ImageUtils.loadTexture('textures/ps.png')} );

However, I encountered an issue when attempting to use the deprecated THREE.ImageUtils.loadTexture method while saving 6 materials in an array and using THREE.MeshFaceMaterial. I now need to use THREE.TextureLoader instead, but I am unsure of how to load 6 textures using this method.

Here is my current code:

function texture()
{
    var loader = new THREE.TextureLoader();
    loader.load( 'textures/ps.png', function ( texture )
    {
        var geometry = new THREE.CubeGeometry( 10, 10, 10 );

        var material = new THREE.MeshBasicMaterial( { map: texture, overdraw: 0.5 } );
        mesh = new THREE.Mesh( geometry, material );
        mesh.position.z = -50;

        scene.add( mesh );
    } );
}

Answer №1

Here is a solution that closely matches what you are seeking:

function LoadTextures(TexturesToLoad, FinalCallback, ResultArray) {
        if (TexturesToLoad.length == 0) return;
        if (!ResultArray) ResultArray = [];
        var loader = new THREE.TextureLoader()
        
        var texture = TexturesToLoad.shift()

        loader.load(texture,

        function (texture) {
            ResultArray.push(texture);
            if (TexturesToLoad.length > 0) {
                LoadTextures(TexturesToLoad, FinalCallback, ResultArray)
            } else {

                FinalCallback(ResultArray)
            }

        },
        ShowProgress,
        ShowError);
    }

    function ShowProgress(xhr) {
        console.log(('Loading ' + xhr.loaded / xhr.total * 100) + '% completed');
    }

    function ShowError(xhr) {
        console.log('An error occurred');
    }

Invoke it with the following:

var TexturesToLoad = []
TexturesToLoad.push("../surfacemap.jpg")
TexturesToLoad.push("../normalmap.jpg");
TexturesToLoad.push("../specularmap.jpg");
    var ReturnedMaterials=[];
    var ReturnMaterials=[];



    var FinalCallback=function(ReturnedMaterials)
    {
            var surfaceMap =  ReturnedMaterials[0];        
            var normalMap =   ReturnedMaterials[1];                    
            var specularMap = ReturnedMaterials[2];         

            var material = new THREE.MeshPhongMaterial( 
            {           
                map: surfaceMap,
                normalMap: normalMap,
                normalScale: new THREE.Vector2( 1, 1 ),
                specularMap: specularMap,
                transparent:false,  
                wireframe: false 
            } );

        var geometry = new THREE.SphereGeometry(100.0, SPHERE_SIDES, SPHERE_SIDES);            
        mesh = new THREE.Mesh( geometry, material ); 
        mesh.rotation.x=Math.PI/2;


    };

    LoadTextures(TexturesToLoad,FinalCallback,ReturnMaterials)

Explanation: The use of a callback function with the THREE.TextureLoader ensures that the resources are loaded when needed. Callbacks can be complex when handling numerous materials. The LoadTextures function allows for recursive calls and ultimately triggers the function of your choice once all materials are loaded. The materials are stored in an array (ResultArray).

Answer №2

There are numerous methods to accomplish this task. Let me demonstrate 2 options;

1) Create your object (cube) by defining its own vertices and faces

.vertices.push( new THREE.Vector3( x, y, z ) );
.faces.push( new THREE.Face3( x, y, z ) );

I have provided a sample in jsfiddle.

2) Utilize UV mapping. Start by preparing the object with UV map in a 3D software such as Blender and export it as a JSON file.

I have also included a demonstration in jsfiddle.

If you are unfamiliar with UV mapping or Blender, refer to tutorials.

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

Transmit information from a comprehensive form using AJAX technology

I created a complex form with 30 fields, out of which 3 fields are repeated 10 times. Here's the code: <form id="artikelform" method="POST" name="controleartikelen" action=""> <table id="controle"> <tr><th>Maakartikel</ ...

Perform an Ajax request with JQuery in an HTML document and transfer the response to a different HTML page

This is my first attempt at using AJAX and jQuery to retrieve data from another HTML page. Below is the code I have written: Here is my JavaScript code: <script type="text/javascript> $(document).ready(function() { $('#submit').click( ...

Loading an Angular app causes Chrome devtools to freeze

Currently, I am facing some unusual behavior in my rather large Angular (1.5) application. When I have Chrome DevTools open while loading the app, the CPU usage of that particular tab shoots up to 100%, causing the app to take a minute or more to load. Add ...

What is the process for incorporating synchronous tasks within an asynchronous function?

const fs = require('fs') const readline = require('readline') const stream = require('stream') const rl = readline.createInterface({ input: fs.createReadStream('logs.txt') }) var uniqueItems = new Set() // ASY ...

Utilizing browser's local storage to dynamically update text in buttons and panels

In my file, I have the following code snippet (I've removed other irrelevant code) <div data-role="panel" id="loc_panel"> <h2>Panel Header</h2> <p>info about this stop</p> </div> <!-- /panel --> < ...

Guide to integrating various HTML files into a single HTML file with the help of Vue.js

Although I am familiar with using require_once() in PHP, unfortunately, I am unable to use PHP in my current project. I attempted to use w3-include from W3Schools as an alternative, but encountered issues with loading my scripts. Even utilizing JavaScript ...

Fixed position not being maintained after clicking the button

Looking for some help with a fixed header issue on my website. The header is supposed to stay at the top while scrolling, which works well. However, when I switch to responsive view, click the menu button, and then go back to desktop view, none of the po ...

"NextAuth encounters an issue while trying to fetch the API endpoint: req.body

Trying to implement authentication in my Next.js app using NextAuth.js, I've encountered an issue with the fetching process. Here's the code snippet from the documentation: authorize: async (credentials, req) => { const res = await fetch ...

Traversing a deeply nested array of objects, comparing it with a separate array of objects

I am currently learning Javascript and facing a challenge involving looping through nested arrays of objects and filtering another array based on specific properties. Let's take a look at the structure of both arrays: const displayArr = { section ...

Is it possible to swap out a color, such as black, in textured images?

Looking to create transparent clouds on a high-resolution planet image. Unfortunately, only have a JPG file but hoping to find a way to remove the black background. Here's the image in question: ...

Surprisingly stumbled into the 'restricted' directory while switching the current directory to a temporary folder

I've encountered a strange issue while attempting to create and switch the working directory to a temporary folder using Node.js. Check out the code snippet below: var path = require('path') var fse = require('fs-extra') var TEST ...

Revealed the previously hidden private variables within the Revealing Module Pattern

I have encountered an issue while implementing the Revealing Module Pattern, as I am struggling to expose a modified private property. var myRevealingModule = (function(){ var name = 'Samantha'; function updateName () { name = ...

Encountered an error while trying to load a resource: the server returned a 404 (Not Found) status code while attempting to edit a form using

I am facing an issue with navigating to the correct path after editing a form in React. Following the update, the web page refreshes and unexpectedly logs me out of the site even though there are no errors detected during the process. The console displays ...

Ways to update the div's color according to a specific value

Below are the scripts and styles that were implemented: <script src="angular.min.js"></script> <style> .greater { color:#D7E3BF; background-color:#D7E3BF; } .less { color:#E5B9B5; background-co ...

Mastering Angular 4: The ultimate guide to managing multiple classes using ngClass

I want to customize my navigation links to resemble file folder tabs by dynamically adding and removing classes using Angular. When a link is active, it should not have a bottom border to indicate it as the primary tab. Here's a rough starting point: ...

Retrieve the outer-HTML of an element when it is clicked

I am working on a project to develop a tool for locating xpath, and I am seeking the most efficient and user-friendly method for allowing the user to select the desired element on a webpage. Ideally, this selection should be made with just a single click, ...

Chrome's inability to efficiently handle chunked responses in comparison to Firefox and Safari

I am currently working on a unique test node server that sends chunked responses every two seconds with the specified headers: response.setHeader('Content-Type', 'text/plain') response.setHeader('Transfer-Encoding', 'chu ...

HTML or JS/jQuery can create disorienting cursor behaviors

Is there a way to create a distorted or crooked mouse movement on a webpage, even though the user is moving the mouse normally? I'm exploring ways to simulate the experience of a Parkinson's or arthritic patient trying to navigate a web page wit ...

How to override the styling of a parent element in CSS

I'm encountering an issue with my website's sidebar. I've set the background color to yellow for elements with the currentPage class. This works fine for the 'Home' tab, but when I try to do the same for a nested tab like 'tag ...

Error 504: The timeout issue occurred during an ajax call

When I make an ajax call to process a large amount of data and then reload the page upon success, I encounter a 504 Gateway Timeout error. The ajax call is initiated with the following parameters: $.ajax({ type:'POST', cache:false, a ...