Unexpected glitch: three.js texture turns completely black

I am currently working on a simple geometry box that I want to decorate with a texture. However, the box seems to be invisible or completely black. This issue is related to a previous question that can be found here. Following the answer provided by gaitat regarding the original question, I updated the code accordingly. To showcase this new problem, I created another test site. The content of the site is as follows:

"use strict";

// make DOM elements:
var container = document.createElement( 'div' );
document.body.appendChild( container );
var info = document.createElement( 'div' );
container.appendChild( info );

// a 'Box2' geometry instance:  (see geometry implementation below)
var myBox2geom = new THREE.BoxGeometry( 100, 100, 100, 10, 10, 10 );  // args: x,y,z-dimensions and width of their segments

// create scene:
var scene = new THREE.Scene();

// make a corresponding 'Box2' mesh:
new THREE.TextureLoader().load(
"http://mrdoob.github.io/three.js/examples/textures/crate.gif",
function ( texture ) {
texture.minFilter = THREE.NearestFilter;
var material = new THREE.MeshLambertMaterial( { map: texture, side: THREE.DoubleSide } );
var myBox2mesh = new THREE.Mesh(myBox2geom, material);
// add mesh to scene:
scene.add( myBox2mesh );
},
function () {},  // onProgress function
function ( error ) { console.log( error ) }  // no error gets logged
);

// make light:
var light = new THREE.PointLight( 0xffffff );
light.position.set(100, 200, 300);
light.lookAt( new THREE.Vector3( 0, 0, 0 ) );
scene.add( light );

// make camera:
var camera = new THREE.PerspectiveCamera( 45, window.innerWidth / window.innerHeight, 1, 10000 );
camera.position.x = 100;
camera.position.y = 200;
camera.position.z = 300;
camera.lookAt( new THREE.Vector3( 0, 0, 0 ) );
scene.add( camera );

// make renderer:
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
container.appendChild( renderer.domElement );

// aaaand render!
renderer.render( scene, camera );
...


...

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
  </head>
  <body>
    <script src="https://raw.githubusercontent.com/mrdoob/three.js/master/build/three.js"></script>
    <script src="main2.js"></script>
  </body>
</html>

Answer №1

Upon reviewing the code, it was identified that there were three errors highlighted by Falk Thiele and 2pha/gaitat:

  1. An issue with Cross-origin resource sharing (CORS) resulted in a SecurityError being displayed in Firebug:

     SecurityError: The operation is insecure.
     gl.texImage2D.apply( gl, arguments );
    

    Falk Thiele suggested resolving this error by setting the CrossOrigin attribute to empty like so:

     var loader = new THREE.TextureLoader();
     loader.crossOrigin = "";
     loader.load(
         "http://mrdoob.github.io/three.js/examples/textures/crate.gif",
         function( texture ) {
             //...
         },
         function () {},  // onProgress function
         function ( error ) { console.log( error ) } // onError function
     );
    

    It's worth noting that a CORS-error can still occur (in Chrome) when loading the crate.gif texture locally even with the

    loader.crossOrigin = "";
    line included. Hence, using this line should be done cautiously only when certain about cross-site origin.

  2. The scene was rendered only once due to the asynchronous nature of TextureLoader.load(), leading to rendering happening before the texture finished loading.

  3. The script encountered issues in Chrome for two reasons: CORS-related problem as mentioned earlier, and also failure to load the THREE library (

    Uncaught ReferenceError: THREE is not defined
    ). The reason behind THREE failing to load in Chrome remains unknown, but in the corrected code (available below and also here), the error is resolved.

A demo showcasing the corrected code can be accessed via JS fiddle here.

Here is the updated code snippet without errors 1, 2, and 3:

"use strict";
// Code block shortened for brevity
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c6b2aeb4a3a386f6e8f7f4f4e8f6">[email protected]</a>/build/three.min.js"></script>

Additionally, a fourth type of error causing white or black textures may arise from no lights present, lights not added to the scene correctly, incorrect light directions, or lights positioned too far from the mesh. Consider using light.lookAt() for proper light alignment.

Another reason for texture issues could be if face normals are not outward-facing from the geometry. Further information regarding this can be found in the question here.

Answer №2

The error console indicates that there is another CORS issue:

DOMException [SecurityError: "The operation is insecure."

To resolve this, you can set the CrossOrigin attribute to empty in your code:

var loader = new THREE.TextureLoader();
loader.crossOrigin = "";
loader.load("http://example.com/image.jpg",
    function( texture ) {
        //...
    },
    function () {}, 
    function ( error ) { console.log( error ) } 
);

Answer №3

Encountering problems when trying to load an image from my local computer using nextjs was a challenge. Chrome's security measures prevented me from doing so, prompting me to instead upload the image to and use the provided link, which ultimately resolved the issue. Interestingly, I also noticed that my setup only worked with images on secure (https) connections as opposed to regular (http).

const texture = new THREE.TextureLoader().load('https://i.imgur.com/E5ThRBu.jpeg');
    console.log(textureImage);
    this.material = new THREE.MeshBasicMaterial(
      {
        map: texture,
      })
    this.geometry = new THREE.SphereBufferGeometry(1, 30, 30);

Answer №4

My experience was quite similar but with a different twist: I attempted to display black text on a transparent background, only to end up with a completely black cube. Fortunately, I was able to resolve this by adding color to my texture png file instead of keeping it transparent.

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

Can you provide guidance on utilizing OneNote JavaScript APIs to interpret indented paragraphs within OneNote?

I keep a notebook that contains the following entries: https://i.stack.imgur.com/MLdO0.png For information on OneNote APIs, you can refer to this link (paragraph class selected already) https://learn.microsoft.com/en-us/javascript/api/onenote/onenote.p ...

Potential dangers involved in sending HTML content through an AJAX request over a secure HTTPS connection

I am exploring the idea of dynamically loading HTML content, such as updating a Bootstrap modal dialog's contents using AJAX calls instead of refreshing the entire page. However, before I proceed, I want to understand the potential risks involved and ...

Improprove the efficiency of rendering cubes in threejs

Here is the code snippet I am working with: https://github.com/CrizzzSombiii/laboratoryofsombiisbycrizz/blob/master/docs/maze2.htm <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/88/three.js"></script> <script> // Code f ...

What is the best method for retrieving data through an ajax call in my modular JavaScript setup?

Working with a basic modular JavaScript structure, my goal is to request a random quote from an API and display it on an HTML page using Mustache.js. I previously achieved this without the modular approach, but now I'm attempting it in a more structur ...

Issue with Heroku deployment: unable to locate JavaScript file

I encountered an issue while deploying my node.js app. Everything seemed to be working fine but it couldn't locate the JavaScript files. The error message displayed was: proove.herokuapp.com/:16 GET 404 (Not Found) Here is the server.js code snip ...

The JavaScript and CSS properties are not functioning properly with the HTML text field

I came across this CodePen example by dsholmes and made some modifications: Here Furthermore, I have developed my own form on another CodePen pen: Link The issue I'm facing is related to the placeholders/labels not disappearing when typing in text f ...

Utilize jQuery to swiftly align elements within a designated container

Check out my JSFiddle example: http://jsfiddle.net/c62rsff3/ I'm attempting to implement snapping behavior between 2 elements using this code: $('.draggable-elements').draggable({ snap: true }); In addition, I've defined a container ...

Utilizing JSON and AJAX to mine data from databases

I've been working on creating a basic "search" box using Javascript, AJAX, PHP, and JSON. I'm focusing on the "world" database that I downloaded from the MySQL website for this particular project. I've hit a roadblock when trying to retrieve ...

Tips for displaying user data from a mongodb database on a webpage, making edits to the information, and then saving the updated data

I have a website where users can register, log in, and update their profile information. However, I am facing an issue where only the data of the first user in the database table is being retrieved. How can I get the data of the currently logged-in user? ...

Why is MutationRecord[] organized as an array in MutationObserver?

I've been diving into the world of MutationObserve, and I've grasped most of it. However, one thing that's puzzling me is why the parameter requires an array. According to the documentation: An array of MutationRecord objects, detailing e ...

How can I convert text containing in Node.js and insert actual new lines instead of the character?

I'm trying to transform a text response by removing special characters like \n and turning them into actual new lines. The initial response contains special characters -----BEGIN MESSAGE----- v1.60 hQEMAwPgeMJUXSL5Bps+U3lC8tnc D8s2Aeb7UtryIRAB ...

Expanding Drop-Down Feature in CodeIgniter: How to Create Nested Dropdown Menus

I'm working on a dropdown menu that is populated with items using a foreach statement. When an item is selected, I need another dropdown menu to appear where specific items can be specified. First Dropdown - Categories (Completed) When a Category is ...

What could be causing my JavaScript loop to replace existing entries in my object?

Recently, I encountered an issue with an object being used in nodejs. Here is a snippet of the code: for(var i = 0; i < x.length; i++) { var sUser = x[i]; mUsers[sUser.userid] = CreateUser(sUser); ++mUsers.length; ...

Is the Packery image grid only functional when the background image is specified in CSS and not in JavaScript? Perhaps we need to look into using Await/Sem

I've successfully implemented a packery image grid that is responsive and functional when the background image in the .item-content section is defined in the CSS file: http://codepen.io/anon/pen/eJdapq .item-content { width: 100%; height: 100%; ...

Why does Cloudinary fail to delete the tmp folder it creates after finishing the upload process?

Recently, I've been working on implementing an upload Post feature for my app. The process involves submitting a file from the frontend, sending it to the backend, and then uploading it to Cloudinary's cloud servers. However, before the upload to ...

MariaDB won't generate JSON output for a column that has a JSON data type

Currently, I am utilizing MariaDB and phpMyAdmin to effectively manage my database. Within one of my tables, I have a specific field that is defined as type json, or alternatively longtext. However, whenever I execute a SELECT query using JSON_EXTRACT(fiel ...

Executing a script that has been inserted into the page post-loading

I'm facing an issue where the script tag at the bottom of my project is not being executed after adding new pages later on. Main const fetch = (url, call) => { var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if ...

Navigating through the complexities of scoping in JavaScript when integrating Node.js

Currently, I am working on an express.js application without using mongoose. My goal is to create a function that can handle calls to MongoDB, pass parameters to it, and retrieve data from the database. However, I have encountered a problem with the foll ...

Leverage the power of Angular and Node.js to dynamically generate and configure a new subdomain on an

Currently, I am tackling a project that involves generating sub domains dynamically based on the prefixes entered by users on my website. While everything is functioning properly on my localhost using diet.js and express-subdomain, errors are being encount ...

Assign the physics settings to a variable within the A-frame

Exploring A-frame () for my scene creation has been exciting. I am curious about how I can dynamically adjust the physics in my virtual world using the A-frame physics component. The goal is to have the physics within my scene be determined by a variable c ...