What techniques can I use to create a three-dimensional appearance for my cube?

Is there a way to achieve a stunning 3D lighting effect similar to the one in this image on my cube below? https://i.sstatic.net/xjCoD.png

When I switch from using BasicMaterial to MeshPhongMaterial or any other material, I end up with a black cube instead.

var camera = null;
var scene = null;
var renderer = null;
var cube = null;
var angle = null;

initialize();
renderer.render(scene, camera);

function initialize() {

camera = new THREE.PerspectiveCamera(1, 1);
camera.position.z = 200;
    camera.position.set(50, -300, 100);
    camera.lookAt(0, 0, 0);

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

clock = new THREE.Clock();

//
renderer = new THREE.WebGLRenderer({
antialias: true,
alpha: true
});
let container = document.getElementById('container');
renderer.setSize(container.offsetWidth, container.offsetHeight);
container.appendChild(renderer.domElement);

let cube2 = generateCube();
cube2.name = "cube2";
//       cube2.position = new THREE.Vector3(1, 0)
scene.add(cube2);

}

function generateCube() {

// GEOMETRY

// 1. Initialize an empty geometry
let geometry = new THREE.Geometry();

// 2. Adding vertices to the geometry
geometry.vertices.push(
// verts [0-3] are in in +z
new THREE.Vector3(-1, 1, 1),
new THREE.Vector3(-1, -1, 1),
new THREE.Vector3(1, -1, 1),
new THREE.Vector3(1, 1, 1),
// verts [4-7] in -z
new THREE.Vector3(-1, 1, -1),
new THREE.Vector3(-1, -1, -1),
new THREE.Vector3(1, -1, -1),
new THREE.Vector3(1, 1, -1),
);

// 3. Connecting vertices in a specific order to create faces
let b = 0x1db0ec;
let y = 0xffef3a;
let r = 0xea353d;
let w = 0x00ff00;

// Setting half faces
geometry.faces.push(new THREE.Face3(0, 1, 2)); // blue
geometry.faces.push(new THREE.Face3(0, 2, 3)); // yellow
geometry.faces.push(new THREE.Face3(5, 4, 6)); // white
geometry.faces.push(new THREE.Face3(6, 4, 7)); // red

// Setting entire faces
geometry.faces.push(new THREE.Face3(1, 0, 5)); // blue
geometry.faces.push(new THREE.Face3(5, 0, 4));
geometry.faces.push(new THREE.Face3(1, 5, 2)); // white
geometry.faces.push(new THREE.Face3(5, 6, 2));
geometry.faces.push(new THREE.Face3(2, 6, 3)); // red
geometry.faces.push(new THREE.Face3(3, 6, 7));
geometry.faces.push(new THREE.Face3(0, 3, 4)); // yellow
geometry.faces.push(new THREE.Face3(3, 7, 4));

// Setting face colors
geometry.faces[0].color.setHex(b); // Half face
geometry.faces[1].color.setHex(y);
geometry.faces[2].color.setHex(w);
geometry.faces[3].color.setHex(r);
geometry.faces[4].color.setHex(b); // Whole face
geometry.faces[5].color.setHex(b);
geometry.faces[6].color.setHex(w);
geometry.faces[7].color.setHex(w);
geometry.faces[8].color.setHex(r);
geometry.faces[9].color.setHex(r);
geometry.faces[10].color.setHex(y);
geometry.faces[11].color.setHex(y);

// MATERIAL

// Creating a material
let material = new THREE.MeshBasicMaterial({
// color: 0x00FF00,
vertexColors: THREE.FaceColors,
wireframe: false,
});

// MESH

let cube = new THREE.Mesh(geometry, material);
return cube;
}
#container {
      width: 20em;
      height: 20em;
    }
<script src="https://threejs.org/build/three.min.js"></script>

        <div id="container"></div>

Answer №1

To enhance the visual appeal of your scene, it is essential to incorporate a light source. MeshPhongMaterial leverages a Blinn-Phong model for reflectance calculation rather than physically based methods.
Without a proper light source, objects will appear entirely black as no light reflections occur.

For instance, consider utilizing AmbientLight and DirectionalLight:

let ambientLight = new THREE.AmbientLight(0x404040);
scene.add(ambientLight);

let directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight.position.set(1,1,1);
scene.add(directionalLight);

In addition to implementing light sources, it is necessary to calculate the reflection of light by considering normal vectors.
You can achieve this by employing .computeFaceNormals() to compute face normal vectors:

let material = new THREE.MeshPhongMaterial({
    vertexColors: THREE.FaceColors,
    wireframe: false});

geometry.computeFaceNormals();
let cube = new THREE.Mesh(geometry, material);

Refer to the following code snippet example to gain insights:

// JavaScript code block
var camera = null;
var scene = null;
var renderer = null;
var cube = null;
var angle = null;

// Function definition to initialize
function init() {
  
  camera = new THREE.PerspectiveCamera(1, 1);
  camera.position.z = 200;
  camera.position.set(50, -300, 100);
  camera.lookAt(0, 0, 0);
  
  // Create a scene object
  scene = new THREE.Scene();

  let ambientLight = new THREE.AmbientLight(0x404040);
  scene.add(ambientLight);

  let directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
  directionalLight.position.set(2,-3,1);
  scene.add(directionalLight);

  clock = new THREE.Clock();

  //
  renderer = new THREE.WebGLRenderer({
  antialias: true,
  alpha: true
  });
  let container = document.getElementById('container');
  renderer.setSize(container.offsetWidth, container.offsetHeight);
  container.appendChild(renderer.domElement);

  let cube2 = createCube();
  cube2.name = "cube2";
  scene.add(cube2);
}

// Function to create a geometric cube
function createCube() {

  // Initialize geometry
  let geometry = new THREE.Geometry();

  // Add vertices to geometry
  geometry.vertices.push(
  new THREE.Vector3(-1, 1, 1),
  new THREE.Vector3(-1, -1, 1),
  new THREE.Vector3(1, -1, 1),
  new THREE.Vector3(1, 1, 1),
  new THREE.Vector3(-1, 1, -1),
  new THREE.Vector3(-1, -1, -1),
  new THREE.Vector3(1, -1, -1),
  new THREE.Vector3(1, 1, -1),
  );

  // Connect vertices to form faces with colors
  let b = 0x1db0ec; // Blue color
  let y = 0xffef3a; // Yellow color
  let r = 0xea353d; // Red color
  let w = 0x00ff00; // White color

  geometry.faces.push(new THREE.Face3(0, 1, 2)); // Half face blue
  geometry.faces.push(new THREE.Face3(0, 2, 3)); // Half face yellow
  geometry.faces.push(new THREE.Face3(5, 4, 6)); // Half face white
  geometry.faces.push(new THREE.Face3(6, 4, 7)); // Half face red

  geometry.faces.push(new THREE.Face3(1, 0, 5)); // Whole face blue
  geometry.faces.push(new THREE.Face3(5, 0, 4));
  geometry.faces.push(new THREE.Face3(1, 5, 2)); // Whole face white
  geometry.faces.push(new THREE.Face3(5, 6, 2));
  geometry.faces.push(new THREE.Face3(2, 6, 3)); // Whol…
#container {width: 20em; height: 20em;}
<!--script src="https://threejs.org/build/three.min.js"></script-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.min.js"></script>
<div id="container"></div>

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

How can I enhance this conversion function from an Array to an Object in JavaScript?

Looking to construct an object consisting of empty arrays using values as keys. const CATEGORIES = ['apple', 'banana', 'orange'] generateCategoryObject() === { apple: [], banana: [], orange: []} function generateCategoryO ...

React: the props appear to be undefined when they should actually have a value

I have a requirement for my props in the children class to be an array of Event objects. Prior to using it in App.js, I am checking if the array is empty like this: function App() { class Event { constructor(id, title, date){ this.id = id; ...

I am experiencing difficulty scrolling down on my website. Can anyone offer suggestions on how to resolve this issue?

I'm having trouble scrolling on my website and I can't seem to figure out how to add more content. I've tried adjusting the height in CSS, but it didn't work. I'm new to web development and would appreciate any help! Maybe the issu ...

Sending images from an external source to a client using Node.js and Express

I'm struggling with a problem. Assuming I have an external image URL, like this one from IMDb.com, . How can I display this image for the client? Currently, I have this: res.write('<img src="/http://ia.media-imdb.com/images/M/MV5BMTMyMzA5ODI ...

Replicating row with distinct values

I'm experiencing some difficulties with a particular issue. I currently have two tables as shown below: <table id="customFields1" class="table table-bordered table-hover additionalMargin alignment"> <thead> <tr> < ...

Exploring the method of implementing a "template" with Vue 3 HeadlessUI TransitionRoot

I'm currently working on setting up a slot machine-style animation using Vue 3, TailwindCSS, and HeadlessUI. At the moment, I have a simple green square that slides in from the top and out from the bottom based on cycles within a for-loop triggered by ...

Meteor: Transmitting Session data from the client to the server

Below is the code snippet I am utilizing on the client side to establish the Session variable: Template.download.events({ 'click button': function() { var clientid=Random.id(); UserSession.set("songsearcher", clientid); ...

Testing JavaScript performance using the V8 engine

function add(x, y) { return x + y; } console.time("clock1"); for (var i = 0; i < 90000000; ++i) { add(1, 2); add('a','b'); } console.timeEnd("clock1"); function combineText(x, y) { return x + y; } fu ...

The issue of Angular curly braces malfunctioning in some simple code examples reversed my

<head> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"> </script> </head> <body style="padding: 20px 20pc;"> <div ng-app="app"> ...

Getting started with OrbitControls in your Three.js Editor project

After using the Three.js Editor to export a project featuring a simple scene with two boxes, everything appears to be loading correctly. The two boxes are visible through the PerspectiveCamera that was integrated. Now, I am looking to enable mouse wheel co ...

Is it possible to retrieve all data from a single useMemo in React?

I'm trying to optimize my code by using just one useMemo instead of multiple React.useMemo blocks. Here is the current version: const App = () => { const isChecked = React.useMemo(() => { const source = get(data, 'somesource&apo ...

Transform my Curl script into a NodeJS app

I'm trying to replicate the functionality of a curl command within my NodeJS application, but I am facing some difficulties. Any guidance on how to achieve this would be greatly appreciated. curl -H "Authorization: bearer $TOKEN" If I already hav ...

Aframe audio gap control

I am currently working on a scene that includes a looping sound: <a-assets> <audio id="ambience" src="./audio/ambient.mp3" preload="auto"></audio> <a-entity id="ambience_sfx" sound="src: #am ...

Show users who liked a post from 2 different collections in Meteor

How do I retrieve a list of users who have "liked" this post from a collection and display it in a template? Collections: likes: { "_id": 1234, "userId": "1dsaf8sd2", "postId": "123445" }, { "_id": 1235, "userId": "23f4g4e4", "pos ...

Tips for including HTML in a JSON request in ReactJS

Upon sending the request as shown below, the response was successfully received. { "contractId": "siva8978", "html": "<p>PREFERENCE SHAREHOLDER AGREEMENTTHIS AGREEMENT is made on the&nbsp;$$Contract Start Date$$ BETWEEN&nbsp;CRADLE WEALTH ...

Ways to guide users through a single-page website using the URL bar

I currently have a one-page website with links like <a href="#block1">link1</a>. When clicked, the browser address bar displays site.com/#block1 I am looking to modify this so that the browser shows site.com/block1, and when the link is clicke ...

Loading and Manipulating OBJ Models with THREE.js

I am experiencing an issue with accessing an object outside of the event boundaries. When I put the object in an array and check out that array, it appears to be empty; however, within the event scope, it is full. I am seeking a solution for how to acces ...

Encountering an issue with the vue webpack-simple template: Uncaught TypeError - the intermediate value is not recognized as a function

Encountering a peculiar error while trying to create an IIFE method in the main.js file. Follow these steps to reproduce the issue, open the command prompt vue init webpack-simple test cd test npm install test npm run dev Open the main.js file and insert ...

Error message: JavaScript JSON variable undefined in AWS Lambda

My lambda function is being triggered by an IoT rule that sends a MQTT message in JSON format. I am facing an issue where the top level fields are logging correctly, but when it comes to nested objects in the JSON, they appear as "undefined". Even after tr ...

The combination of useEffect and Client component has the power to greatly

As a newcomer to React development, I've encountered a blocking error in my code that isn't being detected by Visual Studio Code. Here's the code snippet for my NavBar component: import React, { useState, useEffect } from "react"; import Ima ...