Scaling and mapping textures onto meshes using Three.js TextureLoader

I have a cube and I'm attempting to project an image onto it. I am using a loading Manager to load the image, but I am encountering an issue where material.map is showing as undefined. I suspect that there may be a problem with scaling. The original image size is 512x512 pixels while the cubes are 20x20x20 units.

Although I have omitted the code related to camera and renderer for brevity, I have included all necessary details in the following interactive code snippet below.

var loadingManager = new THREE.LoadingManager();

loadingManager.onProgress = function (item, loaded, total) {

  //Display loading progress percentage
  console.log(loaded / total * 100 + '%');

}

//Indicate when loading is complete
loadingManager.onLoad = function () {

  //Initiate animation once models have finished loading
  animate();
}

function init() {

  //Create a loader
  var loader2 = new THREE.TextureLoader(loadingManager);

  //Load the texture, and assign it to a material once loaded
  loader2.load("../img/leo.jpg", function (texture) {

    //Should these lines be added?
    texture.wrapS = texture.wrapT = THREE.RepeatWrapping
    texture.repeat.set(boxSize, boxSize)

    //Why is the texture not being displayed properly?
    console.log(texture)

    //The following does not seem to work:
    material1 = new THREE.MeshBasicMaterial({
      map: texture,
      side: THREE.DoubleSide
    });


  })

  var geo = new THREE.BoxGeometry(30, 30, 30)
  var mat = new THREE.MeshBasicMaterial({
    color: 0xb7b7b7
  })
  mesh = new THREE.Mesh(geo, material1)
  scene.add(mesh)

}

//Confirming if the image path is correct by displaying it
var img = document.createElement('img');
img.src = '../img/leo.jpg';
document.getElementById('container').appendChild(img);

The value of 'texture' from the console log shows this: https://i.sstatic.net/pISak.png

https://i.sstatic.net/2PSD3.png

Answer №1

The issue arises from trying to assign the material outside the load function callback of your loader. It should be done inside the callback.

As stated in the documentation for TextureLoader:

  • onLoad - Triggered upon completion of loading.

You need to follow this pattern:

loader2.load("../img/leo.jpg", function(texture) {
      texture.wrapS = texture.wrapT = THREE.RepeatWrapping
      texture.repeat.set( boxSize,boxSize )
      //why is this texture 1 not coming through?
      console.log(texture)

      //neither of these work:
      var geo = new THREE.BoxGeometry(30,30,30);
      material1 = new THREE.MeshBasicMaterial({ map: texture,side: THREE.DoubleSide });

      var mesh = new THREE.Mesh(geo, material1);

        // animation loop
       function animate() {

         requestAnimationFrame( animate );

         render();

        // update stats
        stats.update();
      }

      ...
});

To enhance readability and avoid a callback nightmare, try structuring it like this:

function myInit(texture) {
  ...
}

loader2.load("../img/leo.jpg", myInit);

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

How is the height or width of the Bootstrap modal determined?

I'm having trouble utilizing Jschr's modified Bootstrap-Modal for different modal sizes. I can't seem to understand why some modals appear taller, wider, or have other specific dimensions. For more information, refer to the documentation: ...

Cycle through different models using three.js graphical user interface

I have a scene with multiple models and I am using dat.gui to toggle through them. Previously, I attempted to achieve this by toggling the visibility on/off with the following code: var gui = new dat.GUI(); var controls = { toggleObjects: function(){ g ...

Building a responsive image gallery modal using AJAX in Laravel platform

How can I fix the issue of the modal content briefly appearing when I load my page? I am trying to create an image gallery where a modal opens when an image is clicked. Here is the code in my view.blade.php: <script> $(".li-img").click(function ( ...

Unable to retrieve the value from a textarea when using Shopify Product Options by Bold

I'm currently facing an issue trying to retrieve the value of a textarea using Shopify's Product Options by Bold. The code works fine locally, but when I transfer it over to Shopify, I am unable to get the value. Despite looking at various resour ...

Display a modal dialogue with an image on the initial page load for each user

Working on a project with Angular 11, Angular material, and Bootstrap, I encountered an issue. I want to display a popup ad the first time a user visits the home page. The modal dialog is created using Angular material, and I have it in the ads component, ...

Utilize computed fields in Parse Object queries

Currently, I am working on developing a Parse Server API for a cooking-centered social network. One of the key features I am focusing on is creating a function that retrieves recipes. I want this function to be able to display calculated fields such as t ...

Is there a solution to the Chrome issue "Require user interaction for beforeunload dialogs" that arises while running Cypress tests?

Require user gesture for beforeunload dialogs A new feature has been implemented where the beforeunload dialog will only be displayed if the frame attempting to show it has received a user gesture or interaction, or if any embedded frame has received su ...

Adding Multiple Items to an Express Endpoint

I have a requirement to store multiple objects in my mongo database within an express route. Currently, the process is smooth when I post individual objects (such as ONE casino), as shown below. Instead of repeating this numerous times, I am seeking assist ...

When the background image URL is altered, the button size automatically adjusts

Presently, I am working with a button <input id="fireAction" type="button" class="submit" onclick="disableSubmit('preFlight');"><br> Afterwards, I modify the background image of the button under different circumstances For example ...

What are the steps to create offline documentation for sails.js?

I am looking to integrate offline sails.js documentation into my system. You can find the official documentation for sails.js maintained at this Sails.js Documentation. According to their documentation, they use doc-templater for building the documentati ...

Tips on how to resize, position, and scale an object effectively using three.js

Recently delving into the world of three.js, I decided to experiment with importing models using the gltf loader. Upon loading a specific 3D model, my scene transformed to showcase a mesmerizing view, as depicted https://i.sstatic.net/l4jNy.png. However, ...

Ways to display object data in a snackbar within an Angular application

I am currently working on a snackbar feature that receives notifications from a Web Service and displays whether the Job Execution was successful or failed. To parse the JSON data, I have implemented the following code: this.messageService.messageRec ...

Passing attributes to a pre-loaded component with next/link

import TestAcademy from './test-academy.js'; function MyApp({ Component, pageProps }) { const router = useRouter() const [approved, setApproved] = useState(false) ... return( <Link href='/test-academy' ...

"Adding page-specific scripts with the help of nunjucks and express app: A step-by-step guide

What is the most efficient way to manage scripts that are common for all pages and scripts that are specific to certain pages using nunjucks as the template engine and express 4 as the backend framework? --- site --- public |___js |___ script.js (f ...

Refreshing the current checkbox input field in React

I developed a unique custom weekdays check input field using React.js to display which days are open for customers. By looping through a hardcoded array, each day is rendered with its corresponding input checkbox. The first row shows Monday through Thursda ...

What is the best way to access a private class variable within the sockent.on function in Angular?

export class AppComponent { title = 'my-app'; constructor(private notifyService : NotificationService) {} ngOnInit() { socket.on("laravel_database_chat:test", function(message){ //I AM ATTEMPTING TO INVOKE THE NOTIF ...

Using AJAX to retrieve HTML elements may cause compatibility issues with Jquery

I am facing an issue with my unordered list implementation. Initially, the list is empty: <ul id="showlist"></ul> When the user triggers an AJAX function, the list gets populated like this: <ul> <li>a</li> <li> ...

Is it possible to determine the height of a div after it has been rendered using the .resize method?

In my current structure, <div id="A"> <div id="A1"> <div id="B1"></div> <div id="B2"></div> </div> <div id="A2"></div> </div> A2 and B2 contain tables, while B1 has 4 checkboxes. I&a ...

Material Grid adamantly refused to follow the typical horizontal layout, defying its default behavior

I recently discovered Material-UI and have been trying to get two components to display side by side. However, no matter what I try, it always ends up looking like this: https://i.stack.imgur.com/w1Wyh.png Even though it is the default behavior, the Mate ...

How can I save a frame to use as a reference for rendering a different scene afterwards?

How can I cache a frame and then render another scene based on that frame? I have set up two scenes: one for the physical scene and one for the cursor scene, as the physical scene may remain unchanged. To tackle this issue, I am now using 2 canvases, wit ...