Attempting to add color to a cube using Three.js

Attempting to apply three different colors to a cube in three.js, it appears that there may be a limit on the number of THREE.DirectionalLight objects that can be added to a scene. The lack of mention of such a limit in the documentation has raised questions about whether this restriction truly exists or if there is another factor at play.

http://jsfiddle.net/ZMwfc/

        var renderer = new THREE.WebGLRenderer();
        renderer.setSize( 800, 600 );
        document.body.appendChild( renderer.domElement );

        var scene = new THREE.Scene();

        var camera = new THREE.PerspectiveCamera(
                                        35,             // Field of view
                                        800 / 600,      // Aspect ratio
                                        0.1,            // Near plane
                                        10000           // Far plane
                                    );
        camera.position.set( -15, 10, 10 );
        camera.lookAt( scene.position );

        scene.add( camera );

        var cube = new THREE.Mesh(
                                new THREE.CubeGeometry( 5, 5, 5 ),
                                new THREE.MeshLambertMaterial( { color: 0xFFFFFF } )
                            );
        scene.add( cube );
        // top
        light = new THREE.DirectionalLight( 0x0DEDDF );
        light.position.set( 0, 1, 0 );
        scene.add( light );

        // bottom
        light = new THREE.DirectionalLight( 0x0DEDDF );
        light.position.set( 0, -1, 0 );
        scene.add( light );

        // back
        light = new THREE.DirectionalLight( 0xB685F3 );
        light.position.set( 1, 0, 0 );
        scene.add( light );

        // front
        light = new THREE.DirectionalLight( 0xB685F3 );
        light.position.set( -1, 0, 0 );
        scene.add( light );

        // right
        light = new THREE.DirectionalLight( 0x89A7F5 );
        light.position.set( 0, 0, 1 );
        scene.add( light );

        // left
        light = new THREE.DirectionalLight( 0x89A7F5 );
        light.position.set( 0, 0, -1 );
        scene.add( light );

        renderer.render( scene, camera );

In observing the coloring of the cube's sides - top, bottom, front, back, left, and right - it becomes apparent that only the first four are rendered while the last two are not. Rearranging their order could yield interesting results. Any thoughts?

Answer №1

The rendering engine has a restriction on the number of lights it can display, with a default limit of four.

According to the documentation for three.js:

WebGLRenderer( parameters )

The `parameters` parameter is an optional object that defines the behavior of the renderer. If no parameters are provided, the constructor will use default settings.

...

`maxLights` — Integer, default value is 4

If you pass {maxLights: 6} as a parameter to the renderer's constructor, you can enable up to 6 lights in your scene.

However, having 6 different directional lights just to add color to the faces of a cube might be unnecessary. Instead, you can set the colors directly on the faces and utilize {vertexColors: THREE.FaceColors} when creating the material for a multi-colored cube. Check out this example fiddle using only one light source (with random colors) to see how it can be done differently.

Answer №2

Your code looks good to go!

Check out this demo in action with revision r.53: http://example.com/demo.

You can also find more details in the Updates section,

The latest version no longer requires specifying maxLights in the constructor. Shaders will now automatically adjust based on the number of lights present in the scene.

Updated for version r.53

.

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

Is there a way to adjust the border color of my <select> element without disrupting the existing bootstrap CSS styling?

In my Bootstrap (v4.5.3) form, the select options appear differently in Firefox as shown in the image below: https://i.sstatic.net/3suke.png Upon form submission, I have JavaScript code for validation which checks if an option other than "-- Select an Op ...

Tips on displaying a particular JSON attribute?

After starting with a JSON string, attempting to convert it into a JSON object and then trying to print a specific field (such as firstName), I am getting undefined. What could be the issue here? Thank you for your help! var string = '{"firstName ...

The one-time binding notation does not seem to be functioning as expected in AngularJS version 1.6.4

For our application, we are utilizing AngularJS 1.6.4 to display a large number of rows on a single page. However, when it reaches around 7K entries, the page starts hanging. To tackle this issue, we have opted for one-time binding for those specific pages ...

What could be causing the page to refresh every time a post or update is made using a mock REST API with JSON

I have been using Json-Server to mock API requests, but I'm facing an issue where the page reloads every time I fetch or update a post. I've tried searching for a solution, but haven't found one yet. Interestingly, even though I followed a ...

An npm list is always full of modules

As I prepare to install a package using npm, I noticed that my folder for the new project already has numerous items listed when I run npm list. Is it normal for the folder not to be empty at this stage? Have I made an error somewhere? ...

Inconsistencies in latency experienced when making calls to Google Sheets V4 API

Recently, I've been encountering latency issues with the following code: var latency = Date.now(); const sheetFile = await google.sheets({version: 'v4', auth}); var result = await sheetFile.spreadsheets.values.get({spreadsheetId: shee ...

I seem to have misplaced my installed packages within the node_modules directory

During my project, I utilized git where the node_modules folder was naturally ignored. While working on branch1, I added some dependencies (such as redux) and installed them using npm install. Later, I switched to branch2, which was created at the same tim ...

Communication between React components

For the past couple of weeks, I've been immersed in writing a React prototype using Material UI, and the experience has been nothing short of delightful! Before this project, I used to cram all my components into my main class without paying much att ...

What is causing the premature termination of the for loop?

I am currently utilizing Node.js (with nodemon as the server) to upload an excel file, parse its contents, and then send each row to a MongoDB database. The total number of rows in the array is 476, however, the loop seems to stop at either 31 or 95 withou ...

What does the error message "TypeError: Bad argument TypeError" in Node's Child Process Spawn mean?

Every time I execute the code below using node: var command = "/home/myScript.sh"; fs.exists(command, function(exists){ if(exists) { var childProcess = spawn(command, []); //this is line 602 } }); I encounter this error: [critical e ...

Convert the value of the <textarea> element to HTML encoding

Is there a way to fetch the most recent updated value entered in a textarea and encode it in HTML format? I usually use this code snippet to retrieve the value: $('textarea').val(); // works consistently across browsers However, if the value c ...

Animating content with Jquery Waypoints for a seamless and elegant user experience

Currently tackling a project that requires some jQuery functions beyond my current skill set. Hoping to find some solutions here! The project in question is a one page scroll site, with existing jquery and waypoints functions implemented. Check out the c ...

Tips for capturing audio in flac codec format using JS/AJAX

Is there a way to record audio in flac codec instead of opus codec? I attempted setting the codec to flac like this: let blob = new Blob(audioChunks,{type: 'audio/ogg; codecs=flac' }); I also tried this: var options = { audioBitsPerSecond : ...

Stuck autoplay feature when clicking

There is an issue with the play function in the built-in browser audio player. Initially, it starts automatically with the following code... function play(){ var audio = document.getElementById("myaudio"); audio.play(); } However, when modifying the code ...

Splicing using only one parameter will make changes to the array without deleting the entire array

let myArray = ['a','b','c','d','e']; console.log(myArray.splice(1)); console.log(myArray); Looking at the splice documentation, it mentions that not providing a delete parameter would remove all array item ...

Which names can be used for HTML form tags in jQuery?

Recently, I encountered an issue related to jQuery form serialization which stemmed from naming a form tag "elements". The problem arose when using jQuery $(’form’).serialize(). Here is an example of the problematic code: <form> <input name=" ...

What impact does reselect have on the visual presentation of components?

I'm struggling to grasp how reselect can decrease a component's rendering. Let me illustrate an example without reselect: const getListOfSomething = (state) => ( state.first.list[state.second.activeRecord] ); const mapStateToProps = (state ...

Issues Persist with Bootstrap Tree View - object passed but no output显示

After going through numerous discussions and solving several issues along the way, I have encountered a major problem where there is no output. As mentioned before, I am utilizing Bootstrap Tree View: To establish the hierarchical structure required for ...

Utilizing a shared service for multiple JSON datasets in AngularJS: A beginner's guide

After successfully creating a service that retrieves data from a local JSON file and uses it in a controller to display it in the browser, everything seems to be working well. Here is the code snippet: JavaScript Code: var myApp = angular.module("myApp", ...

The integration of Laravel (Homestead) Sanctum is malfunctioning when combined with a standalone Vue application

After running the command php artisan serve my Laravel application successfully resolves on localhost:8000. I have configured Laravel Sanctum as follows: SESSION_DRIVER=cookie SESSION_DOMAIN=localhost SANCTUM_STATEFUL_DOMAINS=localhost:8080 As for m ...