Attempting to wrap my head around the implementation of callback functions in THREEJS

Below is a snippet of code taken from a THREE.JS example that functions properly. I have used this code to create my own art gallery by reverse engineering it from the three.js code. However, I am puzzled by how materialPainting1 can be utilized in the callback function before it is fully defined. Even though it works flawlessly in the example, in my own code I have resorted to using a fiddle to successfully load the painting.

I would greatly appreciate it if someone could clarify how this mechanism works. How is materialPainting1 being used in the callback function even though it is defined afterward? The code functions well in the example, but in my own implementation, I encountered difficulties loading the painting.

var callbackPainting = function () {
  var image = texturePainting1.image;
  texturePainting2.image = image;
  texturePainting2.needsUpdate = true;
  scene1.add(meshCanvas1);
  scene2.add(meshCanvas2);
  var geometry = new THREE.PlaneGeometry(100, 100);
  var mesh1 = new THREE.Mesh(geometry, materialPainting1);
  var mesh2 = new THREE.Mesh(geometry, materialPainting2);
  addPainting(scene1, mesh1);
  addPainting(scene2, mesh2);

  function addPainting(zscene, zmesh) {
    zmesh.scale.x = image.width / 100;
    zmesh.scale.y = image.height / 100;
    zscene.add(zmesh);
    var meshFrame = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
      color: 0x000000,
      polygonOffset: true,
      polygonOffsetFactor: 1,
      polygonOffsetUnits: 5
    }));
    meshFrame.scale.x = 1.1 * image.width / 100;
    meshFrame.scale.y = 1.1 * image.height / 100;
    zscene.add(meshFrame);
    var meshShadow = new THREE.Mesh(geometry, new THREE.MeshBasicMaterial({
      color: 0x000000,
      opacity: 0.75,
      transparent: true
    }));
    meshShadow.position.y = -1.1 * image.height / 2;
    meshShadow.position.z = -1.1 * image.height / 2;
    meshShadow.rotation.x = -Math.PI / 2;
    meshShadow.scale.x = 1.1 * image.width / 100;
    meshShadow.scale.y = 1.1 * image.height / 100;
    zscene.add(meshShadow);
    var floorHeight = -1.117 * image.height / 2;
    meshCanvas1.position.y = meshCanvas2.position.y = floorHeight;
  }
};
var texturePainting1 = THREE.ImageUtils.loadTexture("textures/758px-Canestra_di_frutta_(Caravaggio).jpg", THREE.UVMapping, callbackPainting),
  texturePainting2 = new THREE.Texture(),
  materialPainting1 = new THREE.MeshBasicMaterial({
    color: 0xffffff,
    map: texturePainting1
  }),
  materialPainting2 = new THREE.MeshBasicMaterial({
    color: 0xffccaa,
    map: texturePainting2
  });

Answer №1

When it comes to texture loading in three.js r.66, it's important to note that the process is asynchronous. This means that the callback function will not be executed until after the texture has finished loading. By this point, your materials will have already been defined.

For best practices, it is recommended to define your materials first before loading textures.

Version: three.js r.66

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

Operators within an observable that perform actions after a specific duration has elapsed

Is there a way in an rxjs observable chain to perform a task with access to the current value of the observable after a specific time interval has elapsed? I'm essentially looking for a functionality akin to the tap operator, but one that triggers onl ...

Having trouble with displaying the modal dialog in Twitter Bootstrap 3?

There seems to be an issue with my Twitter Bootstrap modal as it is not rendering the dialog box correctly, and I'm puzzled about the reason behind this. HTML <p class="text-center btn-p"><button class="btn btn-warning" data-toggle="modal" ...

Is there a way to delete highlighted text without using execCommand and changing the font color

With my current use of JavaScript, I am able to highlight or bold a selected text range successfully. However, I am unsure how to undo the bold and unhighlight the text if the button is clicked again and the selected range is already bolded or highlighted. ...

display alternative text before an image is loaded on the screen

Is there a way to display text instead of an image before the image loads? I have a website with an image as the title, causing the page to load fully before the title image is loaded later. Is there a solution for this issue? ...

Implementing a callback in the app.get function within Node.js: A step-by-step guide

I have a fully functioning website and now I am looking to add some logic and data analysis to it. Below is the code snippet for rendering my /data page: app.get("/data", (req, res) => { const sql = "SELECT * FROM MyMoods"; cons ...

Why isn't my SCO considered complete?

My SCO is very basic, with an empty html page. I am utilizing the pipwerks scorm api wrapper in Chrome dev tools to establish a connection to the LMS, set cmi.completion_status to "completed", and cmi.success_status to "failed" (as outlined in the scorm ru ...

Creating a 3D visualization with three.js

My project requires me to create a 3D scatter graph using three.js. I have attempted to implement the code provided below. While the code is functional, the resulting graph appears more like a 2D representation. Adjusting the camera position can add depth ...

What is the purpose of using $ symbols within NodeJS?

Lately, I've been attempting to grasp the ins and outs of using/installing NodeJS. Unfortunately, I'm feeling a bit lost due to tutorials like the one found here and their utilization of the mysterious $ symbol. Take for instance where it suggest ...

Change elements in real-time

I have a requirement to adjust elements with the class .super-elem by adding an attribute adjusted="true". Initially, I can easily achieve this within the document's ready event : $(".super-elem").attr("adjusted", "true"); However, I may add more . ...

Empty form field when submitting form using ajax in C# MVC

I am encountering an issue while attempting to store form data in a database using $.ajax. The problem lies in the fact that upon submitting the form, the username is being saved as null, whereas the email and password are correctly stored. function Sav ...

Can other JavaScript event listeners be synchronized with an asynchronous event?

My goal is to manipulate a web page using Tampermonkey where there is a button with certain event listeners followed by a redirect. Is it possible for me to insert my own click event handler into the button, which triggers an AJAX request and waits for it ...

Creating a complete webpage using HTML

Is there a method to load an HTML file and execute the embedded javascript to create a complete HTML page programmatically similar to how browsers do? Edit 1 - I am working on an application where I need to extract data from an HTML page on a remote websi ...

Guide to implementing a datepicker on a webpage using Laravel

I am having trouble displaying the datepicker using the code below in my Laravel 4.2 application on Firefox. Is there a better way to display datepickers? Are there any CDNs available for this purpose? <table class="table table-striped"> <t ...

Issue with Route Transition in React Router version 4 when using Styled Components

I am currently in the process of constructing a React Application utilizing React-Router@4, <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5e7d0d4d6c198fddac198f9dad4d1d0c7f5869bd7d0c1d49b83">[email protected]</a> ...

Clicking on navigation does not close Bootstrap dropdown

When I use this code on my HTML page, the dropdown menu appears correctly. However, once I click a link, the menu does not close and remains open. How can I resolve this issue? <div class="col-lg-8 col-md-8 col-xs-2 accordion-menu"> <button t ...

What is the most efficient method for encoding and decoding extensive volumes of data for a JavaScript user?

Currently, I am in the process of developing a standalone Javascript application using Spine and Node.js to create an interactive 'number property' explorer. This application allows users to select any number and discover its various properties s ...

Encountering a script error that reads "TypeError: $ is not defined as a function

I am attempting to send an email using web services in asp.net, utilizing html and sending the information through a jquery ajax function. Below is the html form: <div class="col-md-6"> <h2>DROP ME A LINE</h2> & ...

Tips for Displaying Label Names in Dashboard Charts

Can anyone provide guidance on displaying category names in a chart? To see the relevant code snippet, check row 92 where categories are fetched from an API and connected to products. I am trying to understand how to retrieve data based on category nam ...

Tips for concealing a collapsible navbar menu upon clicking elsewhere (Bootstrap 5)

I am trying to create a collapsible navbar menu: <div class="collapse navbar-collapse" id="navbarCollapsible"> .. menu items .. </div> My goal is to hide the menu whenever a user clicks outside of it (not just when click ...

Inadequate completion of Object.create() method

Here's the code snippet: //Note: x is being pulled from an external source and contains certain values var x = [{ name: 'Michael Lovesllamas Lankford', created: 1338420951.11, laptop: 'pc', laptop_version: null, userid: &apos ...