Textures in ThreeJS that are of type transparent PNG and have

Having trouble understanding an issue I encountered with ThreeJS. There's a basic cube on a page and I've got a PNG image of a white question mark, with the rest of the image transparent. When I apply the texture to the cube;

cubeGeometry = new THREE.BoxGeometry( 5, 5, 5 );
cubeMaterial = new THREE.MeshStandardMaterial( { color: this.cubeColor, flatShading: true, map:new THREE.TextureLoader().load( require("./question-mark.png") ) } );
cubeMesh = new THREE.Mesh( cubeGeometry, cubeMaterial );

The transparent pixels in the PNG turn black no matter what I try. What's even more bizarre is that the white pixels in the PNG are showing up as the color of this.cubeColor - which happens to be orange.

I would expect the cube to be orange with the transparent parts of the PNG taking on that color while the white areas remain white.

Can anyone provide some insight?

What I'm seeing:

The texture:

Answer №1

To apply multiple materials, follow these steps:

  const geometry = new THREE.BoxBufferGeometry(boxWidth, boxHeight, boxDepth);

  // Prepare the geometry to use 2 materials
  geometry.clearGroups();
  geometry.addGroup( 0, Infinity, 0 );
  geometry.addGroup( 0, Infinity, 1 );

  const loader = new THREE.TextureLoader();

  // Create 2 different materials
  const material0 = new THREE.MeshBasicMaterial({
    color: 'orange',
  });
  const material1 = new THREE.MeshBasicMaterial({
    map: loader.load('https://i.imgur.com/iFom4eT.png'),
    transparent: true,
  });

  // Assign the materials to the geometry
  const materials = [material0, material1];
  const cube = new THREE.Mesh(geometry, materials);

For example, make sure to use BoxBufferGeometry instead of BoxGeometry

Note that when combining a color and a texture (map) in a single material, the colors are multiplied with each other. This is important to understand as it will affect the final result.

If you want to change the color of a texture, you can do so by setting the color on the corresponding material itself. Here's an example:

function main() {
  const canvas = document.querySelector('#c');
  const renderer = new THREE.WebGLRenderer({canvas});

  // Rest of the code for the scene setup ...

  // Define the materials and apply them to the geometry ...

  function render(time) {
    time *= 0.001;  
    
    if (resizeRendererToDisplaySize(renderer)) {
      // Adjust camera aspect ratio ...
    }
    
    // Change the color of the second material based on time
    material1.color.setHSL(time, 1, 0.5);

    // Update rotation and render the scene
    cube.rotation.x = time;
    cube.rotation.y = time;

    renderer.render(scene, camera);

    requestAnimationFrame(render);
  }
  requestAnimationFrame(render);

}

// Function for resizing the renderer based on display size ...

main();

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

Swap out the default URL in components with the global constant

Could anyone offer some assistance with this task I have at hand: Let's imagine we have a global constant 'env' that I need to use to replace template URLs in components during build time. Each component has a default template URL, but for ...

Enhancing Bootstrap UI Typeahead to Display Multiple Fields in Results List

Having encountered the same issue as described in this question: Bootstrap-UI Typeahead display more than one property in results list? I made adjustments to the Plunker provided in the answer to fit my requirements: http://plnkr.co/edit/FdkvCUUD3ob7dt2 ...

Before I press enter, what kind of function is evaluated by the Node.JS REPL?

It's interesting how in the Node.JS REPL, the result of the current expression sometimes gets evaluated before hitting enter, which raises questions. I find it puzzling: How does Node.JS determine if I intended to evaluate it or not? Simple calculati ...

What is the best way to retrieve a file's creation date using the file System module in Node.js

I'm having trouble fetching the filename and file creation date to send to a client. I tried using fs.stat which provides birthtime but does not include the filename. So, my question is: is birthtime equivalent to the file created date? How can I sen ...

The mechanism for transferring data from the server to the client using JavaScript is malfunctioning

In my webform, I have a fileupload control and a button. When the button is clicked after selecting a file to upload, the image should be saved and renamed with a unique GUID. protected void btnUpload_Click(object sender, EventArgs e) { string fileNam ...

Leverage jQuery to organize and categorize JSON information received through an Ajax call

I have retrieved the following array from a MySQL database using PDO: [{ "tbl":"1", "orid":"915", "date":"2021-12-30 12:46:48", "flag":0 }, { "tbl":"2", "orid":"914", "date":"2021-12-30 12:46:21", "flag ...

The issue of asynchronous behavior causing malfunctioning of the PayPal button

import { PayPalButton } from 'react-paypal-button-v2' <PayPalButton amount={total} onSuccess={tranSuccess} /> const tranSuccess = async(payment) => { c ...

Sustain information across two pages using Next.js

Recently, I have been considering reorganizing my Next.js webapp to allocate different pages for handling various screens. Currently, I have a component that manages multiple states to determine the screen being displayed. Within the jsx section, I utilize ...

Tips for updating the color, background, and height of the particle background using react-tsparticles

Is it possible to customize color and background in react-tsparticles? Below is an example of a particle configuration file named particle-config.js const particlesConfig = { background: { color: { value: "#232741", }, posi ...

The Android webview encountered an error: XMLHttpRequest failed to load because the specified Origin <url> is not permitted by Access-Control-Allow-Origin restrictions

I have developed an application that loads an entire website in an Android WebView. The native code in the Android project communicates with the webpage using the Android Jockey Library, and vice versa. Everything is working smoothly except for one instan ...

Issue with event listener not functioning properly with dynamically created content using AJAX (only using vanilla JavaScript

I used pure javascript AJAX to dynamically load content into the "test" div. However, when I try to click on a child div at index 6, an alert box is not being displayed as expected. How can I fix the issue with the click event not working? The gets functi ...

Interactive Thumbnail Selection for HTML5 Video

Having trouble with creating thumbnails? I managed to solve the cross-domain issue using an html2canvas PHP proxy. No error messages in the Console, but the thumbnails are unfortunately not showing up - they appear transparent or white. Here is a snippet ...

Tips for preventing duplicate properties in Material UI when using React JS

Incorporating components from Material-UI, I have designed a form where the state of inputs is controlled by the parent component. However, I encountered an error stating "No duplicate props allowed" due to having multiple onChange parameters. Is there a w ...

Opting for <button> over <a>

I am currently working with ReactJS in conjunction with a Bootstrap Nav Bar. Bootstrap utilizes an <a> tag for the navigation buttons. I am aiming to have the buttons scroll down to a different component on the page without resorting to using an href ...

Testing NodeJS Database Functionality using Mocha and Asserting with should.js

Currently, I am in the process of testing my NodeJS application using mocha and should. The issue I am facing is that while the first test executes smoothly, the second one fails with an error of null. Interestingly, both tests result in a valid user being ...

jQuery error: an unexpected token was encountered

I am encountering an issue with an "unexpected token =" error on the line toggleNav = function(evt){ in the code snippet below. Despite going through various similar posts, I am unable to pinpoint why this error is occurring. Any assistance in guiding me ...

how to show an error in a modal window when encountering an error

Using Blazor and Blazorstrap, typically when the server disconnects, an "Error" message is displayed. However, with the BsModal from Blazorstrap, it appears in the background layer, making it unresponsive. How can this be fixed? Is it possible to close the ...

Deciphering JSON data into PHP arrays and variables: A step-by-step guide

As a PHP beginner, I'm struggling to grasp certain concepts related to extracting data from POST requests in PHP. Let me describe my code and the issue I'm facing: I have a serialized array that I convert to JSON before sending it via ajax to PH ...

Failure to send Websocket connection

Currently working on PHP, here's a snippet: $room_array = array(); $room_array[0] = 'room-list'; $room_array['info'] = array('room_name' => $room['room_name'], 'owner' => $username['usernam ...

Tips for effectively handling unique properties of a React component (such as Redux integration and custom CSS) when sharing through NPM distribution

Question: How can custom Redux containers and CSS be effectively managed with NPM? It can be challenging to handle these custom files through traditional package distribution platforms like NPM, especially when they need to be edited in various projects. ...