In three.js, the textured sprite appears totally black

As I embark on my journey with three.js, I have encountered a roadblock in what seems like a trivial task – displaying an image on a sprite. Despite following the instructions provided in the documentation, all I see is a black plane:

<!DOCTYPE html>
<html>
    <head>
        <meta charset=utf-8>
        <title>TEST Sprite</title>
        <style>
            body { margin: 0; background-color:#000; }
            canvas { width: 100%; height: 100%; }
            #glRender {
                position:absolute;
                top: 50px;
                left: 200px;
                min-width: 200px;
                width: 50%;
                min-height: 200px;
                z-index: 1;
                height: 50%;
                border: 10px solid #38272C;
            }           

        </style>
    </head>
    <body>
        <div id="glRender"></div>
        <script src="http://threejs.org/build/three.js"></script>
        <script>
            var scene = new THREE.Scene();
            var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );
            var renderer = new THREE.WebGLRenderer();
            renderer.setSize( window.innerWidth / 2, window.innerHeight / 2 );

            container = document.getElementById( 'glRender' );
            document.body.appendChild( container );
            container.appendChild( renderer.domElement );

            // A simple cube
            var geometry = new THREE.BoxGeometry( 1, 1, 1 );
            var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
            var cube = new THREE.Mesh( geometry, material );
            scene.add( cube );

            // completely black...
            var photoTexLoad = new THREE.TextureLoader().load( 'http://s2.favim.com/610/150817/plage-summer-Favim.com-3137863.jpg' );
            var matPhoto = new THREE.SpriteMaterial( { map: photoTexLoad, color: 0xffffff } );
            var sprite = new THREE.Sprite( matPhoto );
            sprite.scale.set( 2, 2, 2 );
            sprite.position.set( 1, 0, 0.5 );
            scene.add( sprite );

            camera.position.z = 5;

            function render() {
                requestAnimationFrame( render );
                cube.rotation.x += 0.01;
                cube.rotation.y += 0.1;
                renderer.render( scene, camera );
            }

            render();

        </script>
    </body>
</html>

Despite my efforts, all I can see is the spinning green cube overlapping with a black plane. What could I possibly be missing to successfully display the image on the plane?

Answer №1

.TextureLoader().load() operates asynchronously. If you attempt to use it immediately after calling it, you may encounter a black plane in your code as the texture is likely still loading.

To resolve this issue, consider:

1. Providing a callback function to .load as a second parameter. This callback will be executed once the texture has completed loading:

var matPhoto,
    sprite,
    texloader = new THREE.TextureLoader();

texloader.load('http://s2.favim.com/610/150817/plage-summer-Favim.com-3137863.jpg', 
   function(tex) {
      matPhoto = new THREE.SpriteMaterial( { map: tex, color: 0xffffff } );
      sprite = new THREE.Sprite( matPhoto );
      //...etc...
   }
);

2. Utilizing an event listener:

var texloader = new THREE.TextureLoader();

texloader.load('http://s2.favim.com/610/150817/plage-summer-Favim.com-3137863.jpg');

textureLoader.addEventListener('load', function(event){

   // event.content contains the loaded texture---------------v
   matPhoto = new THREE.SpriteMaterial( { map: event.content, color: 0xffffff } ); = event.content;

});

Answer №2

Recently, I encountered the "CORS" issue mentioned in this post about texture appearing all black in Three.js: three.js: texture goes all black

Although my code is functioning properly, I am facing difficulties loading images from external websites or directly from my computer. Currently, I can only access files on localhost.

To test this issue, I have resorted to using a specific instance of Google Chrome by launching it through a desktop shortcut with the following command: "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --args --user-data-dir="C:/Chrome dev session" --disable-web-security

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

Add an event listener ".on()" to a button that is dynamically generated

One of the buttons on my page is added dynamically using mustache. It has a specific class assigned to it, but when I try to click on it, the JQuery method does not get executed. This is what my HTML looks like initially: <div id="layout"></div&g ...

Ajax call encounters 404 error but successfully executes upon manual page refresh (F5)

I am encountering a frustrating issue with my javascript portal-like application (built on JPolite) where modules are loaded using the $.ajax jquery call. However, the initial request fails with a 404 error when a user first opens their browser. The app i ...

Integrating Typeform into a React application with a custom button component

I'm facing a challenge with integrating a Typeform contact form into my Gatsby React website. Most of the examples I've come across demonstrate using a basic html button, which doesn't align with the overall theme of my website. Below is the ...

Using an External JavaScript Library in TypeScript and Angular 4: A Comprehensive Guide

My current project involves implementing Google Login and Jquery in Typescript. I have ensured that the necessary files are included in the project: jquery.min and the import of Google using <script defer src="https://apis.google.com/js/platform.js"> ...

What are the best ways to establish communication among JavaScript modules?

I have multiple modules in my application, each with their own responsibilities, but I'm unclear on how they should communicate with one another. What is the best way for modules to interact with each other? How can modules notify or listen to e ...

Transforming a sequence of characters into a multidimensional array

I have a nested for loop that generates an empty string value representing a multidimensional array. After the loops finish, the output looks like this: "[[0,0,0,0],[0,0,0,0]]" Now, I want to insert this into a multidimensional array within my code. How ...

Issues arise when attempting to utilize Async/Await with a gRPC method

Here is the code snippet used to initialize a gRPC server: export const initServer = async (finalPort: number): Promise<string> => { let initStatus = 'initial'; gRPCserver.addService(webcomponentHandler.service, webcomponentHandler.h ...

Select just one picture for emphasis

I have a collection of images on display and I am looking to make edits to specific image details. My goal is to be able to click on an image to highlight it, and then use the edit button to make changes. Currently, the functionality is in place, but I&a ...

Is it possible to design a collapsible element that gives a sneak peek of its content before fully expanding?

In the title, I mentioned that I require the collapsible to display its content partially before expanding and then fully after expanding. To illustrate this concept, here are two drawings for reference: https://i.sstatic.net/f4CHh.png https://i.sstatic. ...

Leveraging oEmbed - JSON data (within client-side JavaScript)

Is it feasible to utilize an oembed provider that solely produces json and xml outputs on the client side using javascript (through a $.ajax request to the provider)? Do we need to rely on oembed providers that enable a jsonp callback in javascript for th ...

Handling Errors Globally in Angular 4

https://i.sstatic.net/ffKEs.png Attached is my code implementing a global handler. I am trying to extract the 'dashboard' from the 500 Error on zone.js. How can I achieve this within the global Handler? Is there a method to obtain the desired ou ...

developing a loading animation with progress indicator in CSS3

I have been working on creating a preloader, but I am having trouble embedding the percentage with the CSS circle. So far, I have tried various plugins without success. Can anyone help me with this issue? Here is my current progress. Below is the HTML co ...

Unable to update values in Google Sheets using the node.js API

I have been working on a node.js project that involves extracting the location of a cell based on a person's name and date. While I am able to determine this information easily, I encounter difficulties when trying to update the cell using the .update ...

Why is this basic HTML code not functioning as expected?

I attempted to combine HTML and JS to change the color of a box upon clicking it, but after reviewing the code multiple times, I am unable to pinpoint the issue. <!doctype html> <html> <head> </head> <body> <d ...

Error in the sequence following Axios subrequest

I am currently working on implementing a search functionality using the Wordpress API. Although I am able to successfully make requests, I am facing an issue where the results are not ordered as expected after my initial request. Let me explain the situati ...

Storing `this` in a variable that is assigned by an element using inline JavaScript is applicable for either all elements or specifically the active element that contains the assigned value

Consider this scenario: if we include the this attribute in an element's onclick event like onclick="a=this", are we selecting the "p" element or can we use the variable a as an alternative to this? Take a look at this code snippet- <p onclick=" ...

The AJAX POST request encountered an error

I apologize for the lackluster title. Basically, when the script is executed, it triggers an 'error' alert as shown in the jQuery code below. I suspect that the issue lies in the structure of my JSON data, but I'm uncertain about the necess ...

Guide to dynamically loading customer data into an HTML table using JavaScript

I'm looking to populate a table with data on customers including their name, customer ID, and rental cost. Can anyone help me with the JavaScript code needed to insert this data into rows of the table? Your assistance is greatly appreciated. Below is ...

Identifying the element with the specified ID within the table's <th> tag in JavaScript

I want to create a table with the title: Summary Statement as of August 3, 2017 at 12:55 The date is functioning properly using JavaScript in other parts of the code, but not in this section. Is there a specific technique I should be aware of? The rest of ...

utilize jquery ajax to input various data

I am attempting to include multiple data in a jQuery ajax call. However, my current implementation is not working as expected. The data fetched is taken from the following span: <span id="<?php echo $tutorial_id; ?>" modes="<?php echo $modese ...