What is the process for changing colors once vertex colors have been updated?

Explaining the issue with an example. I have included a brief snippet of HTML code here to demonstrate the problem. In this scenario, I have created a simple triangle geometry as a global variable. By clicking the "Red" button, function red() is invoked to display the triangle in red color. The challenge arises when attempting to render the triangle in green by clicking the "Green" button if it has already been displayed in red.

<html>
    <body>
        <div id="container"></div>
        <button onclick="red()">Red</button>
        <button onclick="green()">Green</button>

        <script src="http://threejs.org/build/three.js"></script>
        <script>
        //Code snippets for initialization
        var w=300;
        var h=300;
        var renderer = new THREE.WebGLRenderer({antialias: true});
        renderer.setSize(w, h);
        document.getElementById('container').appendChild( renderer.domElement );

        var scene = new THREE.Scene();
        var light = new THREE.DirectionalLight(0xffffff);
        light.position.z = 10;
        scene.add(light);

        var camera = new THREE.PerspectiveCamera( 20, w / h, 1, 1000 );
        camera.position.z = 10;

        var materials = [new THREE.MeshPhongMaterial( { color: 0xffffff, shading: THREE.FlatShading, vertexColors: THREE.VertexColors, shininess: 0 } )];

        //Creating the geometry        
        var shape = new THREE.Shape();
        shape.moveTo( 0,0 );
        shape.lineTo( 0, 1 );
        shape.lineTo( 1, 0);
        var geometry = new THREE.ShapeGeometry([shape]);
        var obj =  THREE.SceneUtils.createMultiMaterialObject(geometry, materials); 
        scene.add(obj);

        //
        function red()
        {
            change_color(new THREE.Color(0xff0000));
            renderer.render(scene, camera);
        }
        //
        function green()
        {
            change_color(new THREE.Color(0x00ff00));
            renderer.render(scene, camera);
        }
        //
        function change_color(color)
        {
            geometry.colorsNeedUpdate = true;
            for(var i=0;i<geometry.faces.length;i++)
            {
                if(geometry.faces[i].vertexColors[0]==undefined)
                {
                    geometry.faces[i].vertexColors[0]=color;
                }
                else
                {
                    geometry.faces[i].vertexColors[0].copy(color);
                }

                if(geometry.faces[i].vertexColors[1]==undefined)
                {
                    geometry.faces[i].vertexColors[1]=color ;
                }
                else
                {
                    geometry.faces[i].vertexColors[1].copy(color);
                }

                if(geometry.faces[i].vertexColors[2]==undefined)
                {
                    geometry.faces[i].vertexColors[2]=color;
                }
                else
                {
                    geometry.faces[i].vertexColors[2].copy(color);
                }
            }
        }

        </script>

    </body>
</html>

Answer №1

It is important to note that altering vertex colors after the initial rendering of a mesh can lead to issues in three.js.

The recommended approach is to avoid using the following method once the object has already been rendered:

geometry.faces[ i ].vertexColors[ 0 ] = color; // assigning a Color object

Instead, it is advised to follow this pattern:

geometry.faces[ i ].vertexColors[ 0 ].copy( color ); // or use set()

Remember to also update the needsUpdate flag when modifying vertex colors:

geometry.colorsNeedUpdate = true;

To ensure smooth operation, include vertex colors in your geometry upon creation and simply adjust the color values as needed.

Version: three.js r.77

Answer №2

Consider declaring your var obj as a global variable and initializing it at the start of your code. Additionally, can you clarify where you are updating the colors - is it within the render function or a separate function?

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

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 ...

Is it possible for promises and $(data).each in jQuery not to work together?

My AJAX handler contains an each() loop to push data into my temp array. However, I am encountering an issue where the array remains empty after the loop. This is puzzling, as I have used promises with each() before without any problems. var temp = []; $. ...

Using javascript and d3.js to display a set number of items on each line through printing

I'm currently working on a project that involves printing a specific number of rectangles per line using d3.js var rectangle = svgContainer.selectAll("rect").data(data).enter().append("rect") .attr("x", function(d,i){ return i*5}) ...

Looking to display a gif when a user clicks a button

I need help with making a spinner gif hidden in Unbounce and then show when the user clicks a button. The button is labeled #lp-pom-button-279 and the image is labeled #lp-pom-image-288 My attempts to use JS and CSS have resulted in the gif being either a ...

Setting a default value for a select option in Angular 2

I am trying to set a default value for an option, acting as a placeholder using this method. It works in pure HTML, but when I implement it with the *ngFor attribute in Angular 2, nothing is selected. Here is the code I use in pure HTML: <select name= ...

Experiencing difficulties with mocha and expect while using Node.js for error handling

I'm in the process of developing a straightforward login module for Node. I've decided to take a Test-Driven Development (TDD) approach, but since I'm new to it, any suggestions or recommended resources would be greatly appreciated. My issu ...

The success callback in the first call will only be triggered when a breakpoint is established

I currently have an ASP.NET MVC webpage with Bootstrap and several plugins integrated. I am attempting to implement a confirmation message using the Bootbox plugin before deleting a record, followed by reloading the page upon successful deletion. Everythi ...

What is the best method for incorporating the three.js GLTFExporter into a TypeScript project?

I have been exploring the use of GLTFExporter in a three.js project written in TypeScript. I started with a basic template from https://github.com/pinqy520/three-typescript-starter and made modifications to the render function as follows: console.log(`typ ...

Exploring the process of setting up a datasource for Select2 in October CMS using the integrated Ajax Framework

Looking to utilize the extensive AJAX framework provided by October CMS to populate a Select2 box with data. The process of using a remote dataset in Select2 involves the following steps: $(".js-data-example-ajax").select2({ ajax: { url: "https://a ...

jquery function context

I'm having trouble grasping function scope in this scenario. When a button is clicked, it triggers a dialog box with a textarea inside displaying a URL that can be copied for camera setup. <button id="axis-details" onclick="apikey('<?php e ...

Dismiss the pop-up box by clicking outside its borders

I have created a unique homepage featuring pop-up boxes with login fields. The background dims when a pop-up appears, and the user should be able to close the pop-up by clicking outside the box boundaries. Although the function closeOverlay works when the ...

When attempting to send emails, SendGrid encounters an error and fails to provide an error code

Earlier today, I successfully sent out a series of emails using SendGrid. It was quite a large number of emails, as I needed to create multiple user accounts with attached email addresses. Thankfully, everything went smoothly and all the emails were delive ...

Node.js - Implementing URL Validation for User Input

I've been utilizing the node module 'request' to develop a job queue for retrieving HTML data from a URL entered by a user. Here's the current state of my code: var jobQueue = []; function processNextJob() { if (jobQueue.length &l ...

Shuffling arrays with JavaScript and jQuery for a touch of randomness

Looking to add some variability to your font choices? I've got an idea for you! How about randomizing three arrays for fonts, font size, and font weight? Then, we can display the results of these arrays in a div with the class name "randomFont." Each ...

When utilizing Solidity Js, upon invoking the function 'get', I encounter an issue displaying the error: "TypeError: Data location must be 'memory' or 'calldata' for return parameter in function"

` //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract MyContract{ string value; constructor() public { value = "MyValue"; } function get() public returns(string) { return value; } function set(string memory _value) publ ...

Is there a more efficient method for coding this switch/case in TypeScript?

I'm working on a basic weather application using Angular and I wanted some advice on selecting the appropriate image based on different weather conditions. Do you have any suggestions on improving this process? enum WeatherCodition { Thunderstorm ...

When attempting to execute a query in Node using oracledb, an error with the code 'npm ERR! errno 3221225477' occurred

Encountered the following error message in the command line: npm ERR! code ELIFECYCLE npm ERR! errno 3221225477 npm ERR! [email protected] start: `node ./bin/www` npm ERR! Exit status 3221225477 npm ERR! npm ERR! Failed at the [email protected] start sc ...

I am trying to figure out the best way to position the navbar directly under the jumbotron in Bootstrap 4

Obtaining information is possible with Bootstrap 3, yet I am struggling to understand how to implement it with Bootstrap 4. ...

What is the process for obtaining a compilation of JavaScript files that are run when an event is triggered?

How can I generate a list of all the JavaScript files that are triggered when a button is clicked or an input field is selected in a complex system? Is it possible to achieve this with Chrome DevTools, or are there alternative solutions available? If Chro ...

Select2.js Dropdown List with Case Sensitivity

Currently making use of select2.js version 4.0.3 Situation: Imagine the dropdown list contains the following options: JavaScript javascript Javascript javaScript So, when a user types in java, all options are displayed (case is n ...