Customizing the appearance of different shapes using colors in three.js

I am having trouble changing the color of individual faces on a rotating cube in my code. Can anyone help me spot what is wrong? Much appreciated.

$(function(){
    var camera, scene, renderer,
    geometry, material, mesh;

    init();
    animate();

    function init() {
        scene = new THREE.Scene();
        camera = new THREE.PerspectiveCamera( 35, window.innerWidth / window.innerHeight, 1, 10000 );
        camera.position.z = 800;

        geometry = new THREE.CubeGeometry( 500, 70, 70 );

        material_1 = new THREE.MeshBasicMaterial( { 
            color: 0xff0000,
            shading: THREE.FlatShading, 
            overdraw: true 
        } );
        material_2 = new THREE.MeshBasicMaterial( { 
            color: 0x00ff00, 
            shading: THREE.FlatShading, 
            overdraw: true 
        } );
        geometry.materials = [material_1, material_2];
        geometry.faces[0].materialIndex = 0;
        geometry.faces[1].materialIndex = 1;
        geometry.faces[2].materialIndex = 0;
        geometry.faces[3].materialIndex = 1;
        geometry.faces[4].materialIndex = 0;
        geometry.faces[5].materialIndex = 1;
        mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() );

        scene.add( mesh );
        renderer = new THREE.CanvasRenderer();
        renderer.setClearColorHex(0x000000, 1);
        renderer.setSize( window.innerWidth, window.innerHeight );
        document.body.appendChild( renderer.domElement );
    }

    function animate() {
        requestAnimationFrame( animate );
        render();
    }
    function render() {
        mesh.rotation.x += 0.01;
        mesh.rotation.y += 0.05;
        renderer.render( scene, camera );
    }
});

Answer №1

The MeshFaceMaterial constructor requires an array of materials to be passed as a parameter.

Rather than:

 mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial() );

You should use:

 mesh = new THREE.Mesh( geometry, new THREE.MeshFaceMaterial( geometry.materials ) );

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

The process of transmitting messages back and forth between a popup script and a content script

I am in the process of developing a Chrome extension that involves sending data requests from a popup script to a content script (via a background script), analyzing the request on the content script, and then sending back a response (again through the bac ...

How can a single item from each row be chosen by selecting the last item in the list with the radio button?

How can I ensure that only one item is selected from each row in the list when using radio buttons? <?php $i = 1; ?> @foreach ($products as $product) <tr> <td scope="row">{{ $i++ }}</td> <td>{{ ...

What is the best method for integrating opensea-js using a script tag in a vanilla HTML/JS environment?

Is there a way to incorporate opensea-js into an html/js project that does not rely on node.js? The source code for opensea-js is only available on github and npm at https://github.com/ProjectOpenSea/opensea-js I came across this link: However, when I tr ...

Achieving perfect alignment of an iframe on a webpage

Having an issue with aligning the iframe on my website. I have two buttons set up as onclick events that connect to internal pages displaying PHP data in tables within the iframe. Despite trying various CSS styles and positioning methods, I can't seem ...

What strategies can I implement to prevent security alerts in Internet Explorer 8 when accessing Google Maps via a secure connection

When using Google Maps on my project through an https connection, I encountered a problem. Interestingly, the issue only arises in certain browsers while others work fine. Despite searching for a solution extensively, I have not been able to find one. Some ...

Using Google-Prettify with AngularJS

I have been attempting to implement Google Prettify in my AngularJS project. It seems to be functioning correctly on the main page, but once I navigate to another route using Angular (after ng-view), it stops working properly. You can check out the plunker ...

Encountered a problem while rendering the app: [TypeError: Unable to assign a value to the property 'content' since it is undefined]. Implementing Express with

My experience with res.render is flawless: res.render('main', function(err, html){ // Displays '<html></html>' from 'views/main.html' console.log(html); }); However, the situation changes when it comes to ...

Managing Emitted Events in Vue.js Components within Components: A Guide

I have created a Toolbar Item component as follows: <template> <div class="flex cursor-pointer items-center justify-center rounded-full border-2 border-gray-300 p-1 shadow-sm transition-all duration-300 hover:scale-110 hover:bg-black ho ...

I am having an issue with my registration form in node.js where it does not redirect after submitting

I am currently working on implementing a registration form using node/express for my website. The routes are all set up and the database connection is established. However, I am encountering some issues when users try to submit the registration form on th ...

Tips for adjusting the color of multi-line text when hovering with the mouse

I'm facing a challenge in changing the color of text when someone hovers over it, but so far I've only been able to make it work if the mouse scrolls over the top border of the text. The text I'm testing is located in the top left corner an ...

React JS simple validator package not functioning properly with post-property date

I am currently utilizing the simple react validator package for form validation in my react JS project. For those interested, you can find the package at this link: https://www.npmjs.com/package/simple-react-validator However, I have encountered an issue w ...

Juicer- Setting restrictions on the frequency of posts

How can I limit the number of posts displayed using the react-juicer-feed component? import { Feed } from 'react-juicer-feed'; const MyFeed = () => { return ( <Feed feedId="<feed-id>" perPage={3} /> ...

Acquiring data from an API response in JSON format using JavaScript

Utilizing a parse.com API server, I have successfully established communication in JavaScript through AJAX. The output from the response is being logged into the browser console with the following code: $.ajax(settings).done(function(response) { ...

Node.js: Extract the object's name and value that are sent from the frontend

I'm in the process of creating a microservice using nodejs. The request is returning the following JSON. { "distCd": "abcd", "distName": "parentLife Distributor (TOD)", "stateCd": "", "subdistInd": false, "maindistInd": true ...

Tips to Avoid Multiple Executions of Javascript Code due to Caching

When I make a request to my Asp.net-MVC application, it returns a partial-view. public ActionResult AccountDetails() { return PartialView("~/Views/partials/Account/Details.cshtml"); } To load the partial view in my form, I use the following ...

Retrieve the next 14 days starting from the current date by utilizing Moment.js

Looking to display the next 14 days in a React Native app starting from today's date. For example, if today is Friday the 26th, the list of days should be: 26 - today 27 - Saturday 28 - Sunday 01 - Monday 02 - Tuesday ............ 12 - Friday Is ther ...

Issues with the Content Editable Functionality

While working on my website, I encountered a strange issue. For some reason, I can't seem to get the contenteditable="true" attribute to work on the heading with the ID "hl". It would be awesome if someone could help me figure out how to mak ...

How can I employ CSS files within a Node module that is compatible with Next?

I recently made the switch from Gatsby to Next and I'm still learning the ropes. When working with Gatsby, I had a Node module that served as my UI library across different projects. This module utilized a CSS module file (style.module.css) that coul ...

Three.js encountered an issue while compiling the fragment shader: The variable 'texture' was not found

Encountering a compiling issue with a fragment shader while working with Three.js. Below is the code I'm using: https://jsbin.com/cigadibeya/3/edit?html,js,output. I attempted to create an animation similar to this example: THREE.WebGLProgram: shader ...

Searching through the Symfony2 database with the help of Select2 and Ajax

Currently, my FAQ System is running smoothly. However, I am looking to enhance it by adding a search function using Select2. Here's what I have so far: Select2 AJAX Script <script> $("#searchall").select2({ ajax: { ...