Issue with ThreeJs: loader failing to load as expected

I've been attempting to add a Texture to my sphere using Three.JS. However, I'm encountering an issue where the function inside the image loading process doesn't execute as expected. Despite verifying that the image is being loaded in the Chrome networking tab.

I'm curious to understand why the function is failing to run.

Below is the code snippet I've utilized in my efforts:

import * as THREE from 'three';
var scene, camera, light, renderer, balltex;


load();

function load() {
    var loader;

    loader = new THREE.TextureLoader(new THREE.LoadingManager());

//  # # #  THIS PART HERE IS THE ISSUE # # #
    loader.load('textures/flakes.png', function(obj) {
        console.log("not running here")
        balltex = obj;
        init();
        console.log("init")
        animate();
    });
}

function init() {
    var height = 500, width = 500, bg = '#000000';
    scene = new THREE.Scene();
    camera = new THREE.PerspectiveCamera(45, height/width, 1, 10000);
    camera.position.set(1.5, 1.5, 1.5);
    camera.lookAt(new THREE.Vector3(0, 0, 0));
    scene.add(camera);
    light = new THREE.AmbientLight(0xffffff);
    scene.add(light);
    var ballmat = new THREE.MeshBasicMaterial({
        map:    balltex
    });
    var ballgeo = new THREE.SphereGeometry( 0.3, 20, 20 );
    var ball = new THREE.Mesh( ballgeo , ballmat );
    scene.add(ball);
    renderer = new THREE.WebGLRenderer({ antialias: true } );
    renderer.setClearColor(bg);
    renderer.setSize(width, height);
    var d = document.createElement('div');
    console.log("here",d)
    document.body.appendChild(d);
    d.appendChild(renderer.domElement);
    var c = document.getElementsByTagName('canvas')[0];
    c.style.width = width + 'px';
    c.style.height = height + 'px'
}

function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
}

“I had anticipated the function to execute without issue, but for some reason, it's not working as intended.”

Additionally, I'd like to note that instead of utilizing THREE.JS CDN, I opted to use npm to manage the library.

Thank you,

Answer №1

  1. Make sure to declare the load() function before calling it in your JavaScript code. Otherwise, it will lead to a reference error.
  2. Avoid passing a new THREE.LoadingManager() to the texture loader as it is unnecessary.
  3. Check if the file path textures/flakes.png is correct and being loaded successfully. Any errors in the console could indicate issues with loading the file.
// 1. Ensure function is defined first
function load() {
    var loader = new THREE.TextureLoader();

    // Callback upon successful loading
    loader.load('textures/flakes.png', function(obj) {
        console.log("Function should now work properly")
        balltex = obj;
        init();
        animate();
    });
}

// 2. Call the function after defining it
load();

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

AJAX Username verification failing to validate

Working with PHP and MySQL, I created a basic form which includes a textfield for the username and a submit button. The page is named checkusername.php. Additionally, I implemented an AJAX function for handling this process. Subsequently, there is another ...

What is the best Bootstrap component to implement?

Can anyone provide guidance on utilising Bootstrap to design the upcoming page? I am interested in understanding which components are suitable for this particular scenario. ...

Modify the style of a newly created div by clicking on it

Exploring vue-cli and encountering a challenge. I've created a row of 24 div elements with the following code: <template> <div class="row"> <div class="hour" v-on:click="colorize" v-for="n in 24"></div> </div&g ...

A buffergeometry boasting over 40,000 vertices

I encountered an issue while loading over 40k vertices into a BufferGeometry. Initially, when I loaded all the vertices at once, the geometry was not rendering entirely. However, after breaking down the geometry into separate chunks of 40k vertices, it st ...

I'm currently facing difficulties trying to implement AJAX with JavaScript and PHP as the desired output is not being

My query is quite straightforward - why isn't the code functioning properly? I am attempting to have the text echoed in PHP displayed inside a div with the ID of "show". Interestingly, this works with a txt file but not with PHP or any other type of f ...

Bootstrap and jQuery for creating columns of equal height

I'm currently utilizing Bootstrap in a web project and struggling to dynamically set the same height for column elements. I am aware of the .row-eq-height class, but using it compromises the responsiveness of Bootstrap elements. My goal is to ensure t ...

Encountering an out of memory error when using cypress to validate a zip file with adm-zip

While attempting to validate the contents of a zip file using adm-zip and cypress, I encountered an out of memory error in cypress. The Zip file may contain .txt, .pdf, .ppt, or .docx files. I am interested in validating the following within the zip file: ...

Collaborating on React components across multiple projects while maintaining the central source code in one repository

I need a solution to effectively share React components, their Flow types, and SCSS between two projects while maintaining the source code in one project. The second project should only have read-only access to these components from the other project. Unf ...

Sending HTML parameters to a PHP file

I have been trying to pass the parameters from the current HTML page to a PHP page using a form. In my header in the HTML, I currently have the following function: <script> function getURLParameter(name) { return decodeURIComponent((new Re ...

Contrasting Template Helper and Template Variable in Meteor.js

What sets apart the use of a Template Helper from a Template Variable (if that's not the right term)? How do you determine when to utilize each one? In the following example, both Template.apple.price function and the quantity function in Template.ap ...

Tips for managing various potential return types in TypeScript?

In my research on the topic, I came across a discussion thread about obtaining the local IP address in Node.js at Get local IP address in Node.js. In that thread, there is a code snippet that I would like to incorporate: import net from 'net'; c ...

An error occurs when trying to access the 'map' property of an undefined variable

Is there a way for me to retrieve the return value for this situation? I attempted to use forEach, but each time I try to loop through the images variable, I encounter the error ("Cannot read property 'map/forEach' of undefined") // Conso ...

Click on the designated button to initiate a new tab

My goal is to show the content of each button in a specific tab when I click one of the 5 buttons, using vue.js. As a beginner with Vue, I've been struggling with this for the past week. Can someone please assist me? Thank you. ...

The initial request is replaced by new information

Trying to fetch data for autocomplete in Laravel. Controller: public function collection_search(Request $request) { $term = $request->search; $serveurapObj = new Serveurap(); $result = $serveurapObj->collectionAutocomplete(); ...

Updates to class variable values in jQuery are failing to take effect

Attempting to create my first JavaScript class has presented some challenges, specifically when it comes to updating a class variable. Despite hours of testing different approaches, I still can't seem to get it right! function ClassName(productId) { ...

Adjust the menu scrollbar position to the right or limit scrolling to within the menu area

$(function() { "use strict"; $(".navbar-toggler").on("click", function() { $(".navbar-toggler").toggleClass("collapsed"); $(".offcanvas-collapse").toggleClass("open"); let menuposition = $("#toggler").offset().left + $("#toggler").width() + ...

Is there a way to modify localStorage without having to refresh the page?

I'm currently working on a shopping cart that pulls products from a json-server. So far, I've successfully displayed the products, added the functionality to add items to the cart, and show the quantity. However, I'm facing a roadblock with ...

Validating an email address without the "@" symbol or if the "@" symbol is the last character

I've been working on validating email addresses using regex, but I'm encountering an issue. The problem is that the validation fails for emails that don't contain the "@" character or have it at the end of the word. For example, if I type "a ...

Struggling to design a responsive layout as the div on the right keeps overlapping the div on the left

I recently built a React component that consists of two columns. In the left column, there's a calendar while the right column contains some text along with an input and select field. However, I noticed that when I resize the window, the elements on ...

Exploring techniques to query a Mongoose/Express array generated from a select multiple option

I am currently working on a search form that utilizes the select multiple attribute. Below is the code snippet for the form. <form action="/search" method="get"> <select name="q" multiple> <optgroup label="Fruit"> <option ...