Mesh does not display texture in three.js

I've been attempting to add a texture to my sphere mesh using the code snippet below:

var loader = new THREE.TextureLoader();
var balltex = loader.load("pic1.jpg");
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);    

However, instead of a textured sphere, I'm just getting a black sphere. I'm not sure what the issue is with the code.
Any help would be greatly appreciated.

Answer №1

It seems like the issue could be related to the texture not finishing loading before the mesh is rendered. To fix this, ensure that the texture(s) are fully loaded before initiating the render loop. There are various approaches to accomplish this, but a simple method involves passing a function to the loader's load() method and triggering the renderer from within it. Here's a revised version of the provided code:

var scene, camera, light, renderer, balltex;

load();

function load() {
        var loader;

        loader = new THREE.TextureLoader(new THREE.LoadingManager());
        loader.load('pic1.jpg', function(obj) {
                balltex = obj;
                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');
        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);
        render();
}

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

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

Download the browser version of UglifyJS 2 now

Is there a way to download the browser version of UglifyJS 2 without having to build it myself? I'm running into issues with the manual installation. I used npm to install uglify-js, but I can't seem to find where to execute the uglifyjs --self ...

The 'Component' you are trying to use cannot be rendered as a JSX component in Next.js

Take a look at the code in _app.tsx: function MyApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} /> } An error is popping up during the project build process: Type error: 'Component' cannot be used as a JSX comp ...

The Heroku system encountered an issue: ENOENT - file or directory not found, trying to access '.env'

I'm encountering issues while attempting to deploy my application to Heroku: Error: ENOENT: no such file or directory, open '.env' 2019-04-10T01:38:23.050188+00:00 app[web.1]: 1 at Object.openSync (fs.js:438:3) 2019-04-10T01:38:23 ...

Transferring data from PHP to AJAX and then injecting it into an SQL query

I've been attempting to pass a datepicker variable into an onclick ajax function, which then sends it to another ajax method that passes the variable to an SQL query. The result of the query is then passed back into the ajax function to generate a cha ...

Concealing Mesh Faces Dynamically in Three.js

Currently, I am utilizing THREE.js version 57 and I am interested in hiding a selected face during run time. Is there a way to achieve this in three.js? Appreciate your help, ...

Easy implementation of environmental mapping in three.js

Trying to create an environment mapping object in a simple way without the usual cubemap is proving to be quite challenging. Interestingly, when using the three.js editor (http://threejs.org/editor/), I was able to achieve this by creating a basic icosahed ...

Use JavaScript to switch the h1 title when selecting an option from the dropdown menu

As a beginner in coding, I am struggling to find a solution using an if statement for this particular problem. Although I can achieve the desired result with HTML code and options, this time I need to use arrays and an if function. My goal is to create a ...

Passing references in React to parent components

Struggling to adopt the react way of thinking, I'm facing an issue with invoking the .submit() method of the form component. Within a material-ui Dialog, buttons are passed via the actions property. Now, I need to trigger the .submit() method of the ...

Execute an AJAX function to monitor a JSON response at intervals of 3 seconds

I'm looking to verify if my user has been updated from another system using JavaScript. Can anyone assist me in creating a function that can analyze a JSON response and determine if it is true or false? The URL /user/updatecheck/ provides a JSON res ...

Use Google script to input drop down options directly into a Google spreadsheet

After gathering coding advice from various StackOverflow examples, I've hit a roadblock while attempting to take my script to the next level. The task seems simple enough, but for some reason, I just can't figure it out. Here's the situati ...

Developing a music playlist using javascript/angular (replicating array elements while linking nested objects)

I am currently working on creating a playlist for a music player within an Angular app that includes a shuffle feature. The actual shuffle function is not the issue, as I am utilizing the Fisher Yates Shuffle method and it is functioning correctly. When th ...

How to fix the Uncaught TypeError: Unable to access the 'open' property of an undefined value in the AppBar + Drawer component with ReactJS and Material-UI?

I'm currently working on implementing the navigation feature in my app using Material-UI framework. I want the default hamburger icon on the left side of the AppBar to open the Drawer component when clicked. However, I keep encountering an error that ...

What is the method for retrieving the data from an XMLHttpRequest response?

Is there a way to use jQuery to query the result of an XMLHttpRequest? For example, let's say I have this code snippet: $.get('somepage.htm', function(data) { console.log($("div.abc").text()); }); The issue is that $("div.abc").text() i ...

The module 'iap_verifier' could not be located

Setting up a new server using the following repository - https://github.com/surespot/web-server. I have successfully installed node.js, npm, CoffeScript, and all required dependencies. apt-get install nodejs npm npm install -g <a href="/cdn-cgi/l/email ...

Is there a discrepancy in the JSON algorithm?

While using google chrome, I encountered the following scenario: I had an object in javascript that looked like this: var b = { text: 'hello world, you "cool"' }; I then used JSON.stringify to convert it to a string and sent it to the dat ...

Is there a way to update an angular.js service object without using extend or copy?

I am working with 2 services and need to update a variable in the first service from the second service. Within a controller, I am assigning a scope variable to the getter of the first service. The issue I am facing is that the view connected to the cont ...

EJS: Is there a way to display multiple populated collections from mongoose in EJS file?

Having trouble rendering multiple populated collections from mongoDB in EJS. To provide more context, I'll share snippets of my code: models, routes, and views. Model Schema var mongoose = require("mongoose"); var playerSchema = mongoose.Schema({ ...

Troubleshooting: React is not defined in Rollup + React 17 with updated JSX Transform

I'm currently working on prototyping a microfrontend architecture using Rollup and multiple create-react-app applications. However, when I try to locally yarn link my external app with the container app, I am encountering the following error: The err ...

Tips for implementing a delay in jQuery after an event occurs

I am working with text boxes that utilize AJAX to process user input as they type. The issue I'm facing is that the processing event is quite heavy. Is there a way to make the event wait for around 500ms before triggering again? For example, if I type ...

Validation for prototype malfunctioning

I am currently using Prototype.js to implement form validation on my website. One of the fields requires an ajax request to a PHP file for validation purposes. The PHP file will return '1' if the value is valid and '0' if it is not. Des ...