The black cube in Threejs is shrouded in darkness, devoid of any unexpected

While exploring a WebGL project, I noticed that other demos have lighting effects present. However, my local code for MeshPhongMaterial on cube 5173 is not displaying the same level of light on all sides. Despite testing various types of lighting options such as pointlight and ambientlight, I cannot seem to identify the root cause of this issue. Upon reviewing the code from other demos, I observed that they use 'let' instead of 'const', although I don't believe this distinction is causing the problem. The perplexing part is why the rotating cube remains black and devoid of any lighting effects.

import './style.css'
import * as THREE from 'three';
import WebGL from 'three/addons/capabilities/WebGL.js';

// Setting up Three.js components
const scene = new THREE.Scene();

const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
renderer.setClearColor(0xeeeeee, 1.0) 
renderer.shadowMap.enabled = true 

document.body.appendChild(renderer.domElement);

const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 100);
camera.position.set(10, 10, 10); 
camera.lookAt(scene.position); 

// Adding lights
const ambientLight = new THREE.AmbientLight(0x404040, 1, 1000)
ambientLight.position.set(10, 10, -10)
scene.add(ambientLight)

const pointLight = new THREE.PointLight(0xffffff, 1,1000)
pointLight.position.set(5, 5, 5)
scene.add(pointLight)
     
// Creating the cube with material
const geometry = new THREE.BoxGeometry(1, 1, 1) 
const material = new THREE.MeshPhongMaterial({
    color: 0x0000ff
})
const cube = new THREE.Mesh(geometry, material) 
cube.position.set(0, 1 , 0)
scene.add(cube)

// Adding wireframeCube
const wireframeCube = new THREE.Mesh(
new THREE.BoxGeometry(2, 2, 2),
new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true })
);
scene.add(wireframeCube);

function animate() {
cube.rotation.x += 0.01
cube.rotation.y += 0.01
}

function render() {
animate()
requestAnimationFrame(render)
renderer.render(scene, camera)
}

// Displaying the scene
renderer.render(scene, camera);

window.addEventListener('resize', function() {
camera.aspect = window.innerWidth / window.innerHeight
camera.updateProjectionMatrix()
renderer.setSize(window.innerWidth, window.innerHeight)
})


if ( WebGL.isWebGL2Available() ) {

// Perform initializations if WebGL2 is supported
render()

} else {
const warning = WebGL.getWebGL2ErrorMessage();
document.getElementById( 'container' ).appendChild( warning );
console.log('Not Support webgl');

}

[![a cube with no light][1]][1] [1]: https://i.sstatic.net/65p8brtB.png

Answer №1

Your code has a few areas that need attention, particularly regarding the camera position, light intensity, and material type.

To begin, adjust the PointLight intensity:

const pointLight = new THREE.PointLight(0xffffff, 1000, 1000);

Next, while the PhongMaterial reacts to light, it can appear flat under certain conditions, especially when zoomed in on the cube. This is due to its simpler shading compared to the Standard Material which uses PBR. Both materials should reflect light, but be mindful of this difference, especially with combinations like PointLight or longer camera distances.

Consider using:

const material = new THREE.MeshStandardMaterial({
    color: 0x0000ff
});

Lastly, try adjusting the camera position:

camera.position.z = 5;

<script type="importmap">
  {
"imports": {
  "three": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5c28342e39391c6c726d6a6a726c">[email protected]</a>/build/three.module.js",
  "three/addons/": "https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c9bda1bbacac89f9e7f8ffffe7f9">[email protected]</a>/examples/jsm/"
}
  }
</script>

<script type="module">
import * as THREE from "three";
import WebGL from 'three/addons/capabilities/WebGL.js';

// Code continues...

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

Incorporate Functionality into AngularJS Controller

Although I have experience with other MVC Frameworks, I am new to AngularJS and facing an issue. My controller is named "Projects" and the route is /projects. However, I want to be able to navigate to /projects/java where a new page template/view will be d ...

What is the best method for finding the value of an element?

Here is the snippet of code that I'm working with: if($('span').text().indexOf("t")){ console.log($('span').text()); } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <sp ...

Is TypeScript checking in VSCode failing to detect await functions?

I have been working on an app that retrieves weather data based on a user's location, and everything seems to be functioning correctly. However, during the coding process, I keep encountering errors that are being flagged, even though the code runs sm ...

What is the best approach for creating unit test cases for recursive functions in node.js using the Mocha testing framework?

( async ()=>{ // code })(); This particular self-invoking function is located within a JavaScript file that has not been exported. I am looking to import it in order to write unit tests, but I have yet to find a solution. I attempted to use the rewi ...

The interface cannot be assigned to the type of Record<string, unknown>

I recently created a generic react component that looks like this: export interface GenericTableProps<T extends Record<string, unknown>> { columns: Column<T>[]; data: T[]; } const GenericTable = <T extends Record<string, unknow ...

Converting a JavaScript object to JSON within Node-RED

I am attempting to convert a JavaScript object created in my Node-RED flow to JSON format, but I am struggling to figure out how to do it. The object consists of an hour and minute displayed on the screen, such as "13:02". I need to see this in JSON format ...

Steps for developing your own node package manager

Looking to create a CLI package manager application called mypkgname for your Github repository? You can easily install this package globally by registering it on npm: npm install -g mypkgname-cli mypkgname init myApp cd myApp npm install npm start Here ...

Retrieving vector layers by class and attempting to refresh them in OpenLayers version 2.14 is unsuccessful

First, the process involves accessing all Vector layers, checking if they are visible and retrieving their names. After that, we need to clear any applied filters on those layers and refresh them. Below is a snippet of the code: var mLayers = map.getLaye ...

Tips for avoiding accidental unit conversion in jQuery

Imagine having the following code: var $element = $('<div/>'); $element.css("margin-left", "2cm"); console.log($element.css("margin-left")); When tested in Chrome, it doesn't return anything, but Firefox shows "75.5833px". Any sugges ...

In my efforts, I am attempting to retrieve a value using JavaScript in order to send it back to PHP in JSON format

I have successfully developed a date selection feature with the chosen date displayed at the bottom (Second box in green). Now, I am looking to extract the user's selection in PHP and then send it in JSON format. Any suggestions or assistance on this ...

What is the best way to activate a function from a modal component without having the function embedded in Angular 14?

I've recently been putting together an e-commerce application using Angular 14. Currently, I'm tackling a form that must only be submitted once the user accepts the "Terms & Conditions" shown in a modal popup. The FormComponent and ModalCompone ...

Is the use of 'use client' always necessary in order to utilize a hook in Next.js?

Is it necessary to include 'use client' in every page that uses useSelector when working with Redux in Next.js? If I don't include 'use client', I encounter this error: - error node_modules\react-redux\lib\component ...

What methods can I use to analyze the integrity of the data's structure?

Currently working on an API using NestJS and typeorm. I am in need of a way to verify the format of the data being returned to clients who make requests to it. For instance, when accessing the /players route, I expect the data to have a specific structure ...

What is the best way to evaluate a sequence of actions and their outcomes?

Recently, I've dived into the world of writing automated tests for a React application. Along the way, I encountered some intriguing questions about the best approach to testing a series of interactions within the app. Let's imagine a scenario w ...

What is the best way to initiate an animation once the one before it has finished?

I am facing an issue with my animation function where all animations play simultaneously. This is not the desired behavior; I would like to play each animation after the previous one ends. Can someone guide me on how to achieve this? canvas = document.get ...

Utilizing JavaScript values instead of relying on HTML values - a step-by-step guide

I am facing a challenge with 3 buttons that I have created: <button id="b1">0</button> <button id="b2">0</button> <button id="b3">0</button> Instead of retrieving the value from the HT ...

how can I determine the selection status of a checkbox using the "this" keyword as an id selector in JavaScript?

function checkSelected() { if ($(this).prop("checked") === false) { alert("was unselected"); counter++; $(this).prop("checked", true); } if ($(this).prop("checked") === true) { ...

Leveraging res.render {objects} within client-side rendering

I admit that I may not be the best, which is why I'm seeking help here. However: con.connect(); con.query('SELECT name, lname, rank FROM players LIMIT 1', function(err,rows, fields){ if(err) throw err; result = rows; resultstring ...

Employing ng-click within a displayed column of Datatable

Currently, I am utilizing a plain Datatable in AngularJS without any Angular-Datatable libraries. Everything appears to be working well except for one issue. Here is the datatable code snippet: $scope.siInfoTable = $('#siInfoTable').DataTable({ ...

Syntax Error Unearthed: Identifier Surprise Discovered in (Javascript, ASP.NET MVC, CSHTML)

I encountered an error when attempting to remove a dynamically created HTML element by clicking the corresponding remove button. The goal is to invoke the remove method at the end of the script and pass along certain arguments. However, I'm facing iss ...