When incorporating multiple BoxGeometries, THREE.js ensures that each box maintains a consistent color throughout. The uniformity remains unchanged

Looking to create a simple program using Three.js to display bars at specific locations with varying heights and colors. As a beginner in Three.js, I am currently exploring the framework.

When running my script to set up the bar positions, colors, lights, camera, and controls, I noticed that the colors of the boxes remain constant even when using MeshPhongMaterial. I could use some assistance in resolving this issue.

// Getting Started
function plotRF(bar_data){
    // Bar Data
    this.bars = bar_data
    // Accessing the canvas for screen sizing 
    this.canvas = document.getElementById("BarCanvas")

    // Creating the scene
    scene = new THREE.Scene();

    // Defining the camera
    camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 8000 );
    camera.position.z = 500;
    camera.position.y = 500;

    // Setting up the renderer
    var renderer = new THREE.WebGLRenderer({ canvas: BarCanvas });
    // Adjusting the render size
    renderer.setSize( this.canvas.width, this.canvas.height);

    // Adding lights
    this.add_lights()
    // Integrating controls
    controls = new THREE.OrbitControls( camera, renderer.domElement );

    // Creating Geometry 
    this.add_bars();

    var render = function () {
        requestAnimationFrame( render );   
        renderer.render(scene, camera);
    };

    render();
};


plotRF.prototype.add_bars = function(){

    // Multiplier for bar height
    var multiplier = 20;

    // Size of the bars
    var lw = 5;

    // Looping through the data
    for (i = 0; i < this.bars.length; i++){
        var geo = new THREE.BoxGeometry( lw, lw, this.bars[i][0]*multiplier );
        
        var rfcolour = this.colorTable(this.bars[i][0]);
        var mat = new THREE.MeshPhongMaterial({
            color: rfcolour,
            emissive: 0x072534,
            side: THREE.DoubleSide,
            shading: THREE.FlatShading
        });

        cube = new THREE.Mesh(geo, mat);
        cube.position.x = this.bars[i][1] / 10;
        cube.position.y = this.bars[i][2] / 10;
        cube.position.z = this.bars[i][0] * multiplier / 2;
        
        scene.add(cube);
        console.log("bar added, x:" + this.bars[i][1] +", y:" + this.bars[i][2] + ", RF:" + this.bars[i][0]);
    }       
};

plotRF.prototype.colorTable = function(RF){

    if (RF < 1 ) {
        return new THREE.Color(255, 0, 0);
    } else if (RF < 1.2) {
        return new THREE.Color(240, 50, 50);
    } else if (RF < 1.4) {
        return new THREE.Color(230, 100, 100);
    } else if (RF < 1.6) {
        return new THREE.Color(220, 150, 150);
    } else if (RF < 1.8) {
        return new THREE.Color(210, 200, 200);
    } else if (RF < 2.0) {
        return new THREE.Color(200, 220, 220);
    } else if (RF < 3.0) {
        return new THREE.Color(150, 220, 220);
    } else {
        return new THREE.Color(100, 240, 240);
    }
}

plotRF.prototype.add_lights = function(RF){

    var lights = [];
    lights[ 0 ] = new THREE.PointLight(0xffffff, 0.8, 500);
    lights[ 1 ] = new THREE.PointLight(0xffffff, 0.8, 500);
    lights[ 2 ] = new THREE.PointLight(0xffffff, 0.8, 500);

    lights[ 0 ].position.set(0, 2000, 0);
    lights[ 1 ].position.set(1000, 2000, 1000);
    lights[ 2 ].position.set(-1000, -2000, -1000);

    scene.add(lights[0]);
    scene.add(lights[1]);
    scene.add(lights[2]);
}

An illustration showcasing the constant colors can be viewed below. Please note that the colors accurately reflect the R,G,B values used in the THREE.Color function.

https://i.sstatic.net/oBhbR.jpg

Answer №1

To achieve the desired colors, follow the instructions outlined in the official documentation. For instance:

return new THREE.Color("rgb(255, 0, 0)"); // Represents the color red

Answer №2

When inputting the values for red, green, and blue directly into the THREE.Color method, they should be within the range of 0 to 1.

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

Occasionally, there are instances when node.js combined with express.js and hogan.js may result in a blank page being

Most of the time, every feature in this app functions properly. However, there are instances when a blank page is displayed instead of the homepage (or any other page). Interestingly, making a minor adjustment to the affected view, such as adding a space o ...

What is the process for incorporating a personalized validation function into Joi?

I have a Joi schema and I am trying to incorporate a custom validator to validate data that cannot be handled by the default Joi validators. Currently, my Joi version is 16.1.7 const customValidator = (value, helpers) => { if (value === "somethi ...

Retrieving information from a MYSQL database table and populating a text field with AJAX and PHP

Is there a way to use AJAX to display the data from an array that is called in getword.php into a text field in index.php? Let's take a look at the code below: Here is the code snippet from index.php: <body> <div class="container" ...

Best practices for retrieving information from the user interface

My journey with NextJS has been a learning experience as I navigate connecting the frontend to the backend. Initially, I attempted to create a Restful API for CRUD operations from the frontend, but encountered authentication issues that left me puzzled. A ...

Is there a way to apply the same class exclusively to the first child within a group?

How can I include specific classes for only the initial group of items in a nested ul li list? <ul> <li class="first-group"> <ul> <li></li> </ul> </li> <li class="first-group"></li> & ...

What is the best way to create a sliding <nav> effect when a <div> is clicked?

Hello! I am looking for a solution that will cause the navigation contents to slide out from the left when the div class "bt-menu" is clicked. It should also slide back in to the left either when the div is clicked again or when anywhere outside of the nav ...

Maintaining selected options in select lists while updating model data in Angular

New to Angular and exploring the Product object with Sku objects nested inside. An app allows users to fetch a product, resulting in the Product object being assigned to $scope.product: var app = angular.module('app', []); app.controller(&apos ...

What is the best way to smoothly scroll to another page using a specific id?

My website consists of multiple pages and I am looking for a code that will allow for smooth scrolling navigation to another page when loading on a specific id or section. For example, in the navbar I have multiple pages with links. When clicking on a lin ...

Retrieve a result by utilizing a nested function in conjunction with the request NPM module

Hello there! I'm currently working on scraping data from the ghost blogging platform using the request package. However, I've run into a bit of a roadblock when trying to return a value of a nested request. I've pinpointed the area that seem ...

Can we verify if this API response is accurate?

I am currently delving into the world of API's and developing a basic response for users when they hit an endpoint on my express app. One question that has been lingering in my mind is what constitutes a proper API response – must it always be an o ...

Apple Automation: Extract a targeted string from text and transfer it to a different spot within the page

Apologies for my lack of expertise in this area, but I hope to convey my question clearly. I am working on a form where I need to input text in order to copy specific items and paste them elsewhere on the same webpage. For example, if the input text is " ...

Can we display the chosen form values before submitting?

Want to implement a confirmation message for users before submitting their form using onClick="return confirm('are you sure ?')". The basic form structure is as follows: <form> <Select name='val[]' class='select'> ...

Link AngularJS service array length property to the controller's scope through binding

I am attempting to connect the length of an array from another service to my controller's scope in the following manner: app.controller('TestCtrl', function ($scope, safePostService) { $scope.count = safePostService.queue.length; $ ...

Leverage the power of Angular to seamlessly integrate jQuery code across your

Interested in incorporating the plugin into my AngularJS project. To achieve this, I have to: $(document).ready( function() { $("html").niceScroll(); } ); The challenge is figuring out where to place this code so that it runs site-wide and ...

After loading Google Maps, initiate an AJAX request

Is there a way to determine if Google Maps has finished loading? I need to send an Ajax request once the map is fully loaded. Currently, I am displaying a group of users on a map with info windows. However, the browser becomes unresponsive due to the larg ...

The React component fails to display updates following a state change

Greetings, I am currently facing an issue with re-rendering the component. Below is the code for the initial screen where a custom component is being utilized: class Ahelle extends React.Component{ constructor(props){ super(props) this. ...

Why does the browser indicate that a GET request has been sent but the promise does not return anything?

Having trouble with a puzzling issue and unable to find any solutions online. I am attempting to make a basic HTTP get request to receive a JSON object from an API I created (using express+CORS). I have experimented with both Axios and VueResource, yet en ...

What could be causing JavaScript fetch to only send OPTIONS requests instead of the expected calls?

I'm having an issue with my AJAX request using javascript fetch. It's only sending an OPTIONS call and not proceeding to make further calls. What's strange is that the response header seems fine, and $.ajax is working as expected. Check out ...

I am attempting to establish a connection with the Converge Pro 2 system from Clearone using NodeJS node-telnet-client, but unfortunately, my efforts to connect have been unsuccessful

My connection settings are as follows: { host: '192.168.10.28', port: 23, shellPrompt: '=>', timeout: 1500, loginPrompt: '/Username[: ]*$/i', passwordPrompt: '/Password: /i', username: 'clearone ...

Is it possible to utilize the addition assignment operator (`+=`) to modify the `transform:rotate('x'deg);` CSS property using

This is the code I have been working on: #move{ height:70px; width:70px; border:2px solid black; border-radius:15px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <input type="button" val ...