Adjust the hue of a Three.js-generated 3D cube

Seeking assistance! How can I customize the colors of a 3D cube in the Three.js library rather than using the default settings?

This is what I have managed to create so far -

HTML

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

JavaScript

// revolutions per second
var angularSpeed = 0.2;
var lastTime = 0;

// this function runs on each animation frame
function animate() {
  // update
  var time = (new Date()).getTime();
  var timeDiff = time - lastTime;
  var angleChange = angularSpeed * timeDiff * 2 * Math.PI / 1000;
  cube.y += angleChange;
  lastTime = time;

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

  // request new frame
  requestAnimationFrame(function () {
    animate();
  });
}

// create renderer
var container = document.getElementById("container");
var renderer = new THREE.WebGLRenderer();
renderer.setSize(container.offsetWidth, container.offsetHeight);
container.appendChild(renderer.domElement);

// set up camera
var camera = new THREE.PerspectiveCamera(45, 
                 window.innerWidth / window.innerHeight, 1, 1000);
camera.position.z = 700;

// establish scene
var scene = new THREE.Scene();

// define cube dimensions and color
var cube = new THREE.Mesh(new THREE.CubeGeometry(400, 100, 200), 
      new THREE.MeshBasicMaterial({
          wireframe: true,
          color: '#ff0000'
}));
cube.rotation.x = Math.PI * 0.1;
cube.rotation.y = Math.PI * 0.3;
scene.add(cube);

// initiate animation
animate();

Here is a Fiddle showcasing it.

Answer №1

MeshNormalMaterial does not have built-in support for manipulating colors with properties like color or Ambient.

To work around this limitation, you can simply use

THREE.MeshBasicMaterial({color:0xFF0000})
with the color property specified.

Alternatively, you can utilize the setHex function to change the color of a previously created material.

For a demonstration, check out this fiddle.

Answer №2

Within this portion:

let box = new THREE.Mesh(new THREE.BoxGeometry(300, 150, 250), 
      new THREE.MeshBasicMaterial({
          wireframe: true,
          color: '#00ff00'

Modify the color in MeshBasicMaterial to the hexadecimal code of your desired color.

I'm facing some challenges trying to load the basic cube example they demonstrated on my web browser...

Answer №3

Enabling the Wireframe option in CSS will cause the cube's color property to be overtaken by the lines or vertices. If you disable wireframe:true, the cube will display its original color...

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

What is the most efficient method for encoding and decoding extensive volumes of data for a JavaScript user?

Currently, I am in the process of developing a standalone Javascript application using Spine and Node.js to create an interactive 'number property' explorer. This application allows users to select any number and discover its various properties s ...

JavaScript: Creating a Function that Returns an Object with an Undefined `this.variable`

While using javascript, I encountered an issue with instance variables. Declaring a variable as "this.variable" works fine until my function returns an object. However, if the function returns a String or Number, there are no issues. But when it returns ...

Tips for preventing nested subscriptions from exceeding two levels

I have four subscriptions that depend on each other. While there are numerous suggestions on avoiding nested subscriptions, they often don't address more than two levels of nesting. How can I prevent so many nested subscriptions? This is the code fo ...

The AJAX request was successful, however, the PHP script did not return any

When using an Ajax success function to alert data in JavaScript, there may be occasions where the PHP side shows that the GET array is empty. <script type="text/javascript"> var myArray={ name:"amr", age:22 } myArray =JSON.stringify(myA ...

Are there problems with the response values of functions that can handle varying object interfaces?

Currently in the process of developing a command line blackjack app with Node and Typescript, even though I am relatively new to Typescript. My main challenge lies in implementing interfaces for player and dealer objects, as well as creating functions that ...

Issue with relative templateUrl in Angular 2 not resolving paths

As I embark on creating my first Angular 2 app, I'm faced with the task of setting my template in an HTML file using `templateUrl`. Currently, both the component.ts and view.html are stored in the same folder under src/ directory. Here's what I ...

Issue with cookies modification in Next.js 14 server actions

I'm currently facing a challenge while working on a Next.js 14 project where I am trying to make changes to cookies. Despite carefully following the Next.js documentation regarding server actions and cookie manipulation, I keep running into an error w ...

Creating a POST method in AngularJS

Here is the code snippet I am working with: var req = { method: 'POST', url: '/customer', headers: { 'Content-Type': 'application/json' }, data: { test: 'testvalue' } }; $http(re ...

"Error: The term 'Readable' is not

When I input this code: const { Readable } = require('stream'); Readable ends up being undefined. However, when I try this code instead: import { Readable } from 'stream'; Readable becomes an empty object with no properties. It&apos ...

JavaScript can be used to open several tabs simultaneously within a single browser window

Looking to open multiple tabs in the main browser? Check out this code snippet: function openSM() { window.open("http://www.google.com","_blank"); window.open("http://www.yahoo.com","_blank"); window.open("http://www.bing.c ...

Determine the appropriate message based on the size of the array

I am encountering an issue where I have a sample document stored in a mongo atlas database: { "_id": { "$oid": "5e517a946364cc48f0ccf1e7" }, "firstName": "checkout1", "lastName": "", "companyName": "", "phoneNumber": null, ...

Leverage the power of v-model props in your Vue 3 component to efficiently retrieve API breakpoints

I am currently working on integrating the API breakpoints in my child component. These components are designed for my football web application. The breakpoints are sourced from: api-football My challenge lies in passing multiple prop values into a c ...

The Bootstrap 4 tooltip is failing to display correctly and is only functional for anchor tags

Utilizing bootstrap 4, I aim to display tooltips on both buttons and anchor tags. However, the tooltips only appear on anchor tags and not on buttons. Furthermore, even when the tooltip does display, it lacks proper styling and appears white without adheri ...

Unable to input text using Python Selenium in a textbox

Currently, I am attempting to input text into a specific textarea HTML element using Python Selenium: <div class="spk-c spH-d"><div id="gwt-uid-23" class="sppb-a"> <div class="sppb-b spk-b">For example, flowers or used cars</div> & ...

transferring information to a different application module (or page) through a double-click feature in AngularJS

Within my angularjs application, I am faced with a challenge involving two pages. The first page retrieves data from a database and displays it in a table. Upon double-clicking on a row, the user is directed to another page where more detailed informatio ...

Guide to Repairing Uncaught TypeError: players.setAttribute is not a recognized method?

I'm a beginner and encountered an error saying Uncaught TypeError: players.setAttribute is not a function when submitting an action. How can I solve this issue? Please share your insights. ''' //selecting all necessary elements const s ...

Concerning Java's Map and Array functionalities

When working with Javascript, we have the ability to create statements like the one below. var f_names = { 'a' : 'Apple', 'b' : 'Banana' 'c& ...

Switching between Login Form and Register Form in VueJS template

Recently, I attempted to switch between the 'Login Form' and 'Register Form' using code that I found on codepen Flat HTML5/CSS3 Login Form. While the code functioned properly on its own, when integrated into a Vue Template, the form fai ...

Having difficulty rearranging choices within an optgroup

This is a dropdown https://i.sstatic.net/Rk5yL.png <select id="officer-id" placeholder="Choose an officer"> <option selected="selected" >----</option> <optgroup id="pt1" label="To be reviewed"> ...

Troubleshooting Angular JS loading problems

I'm attempting to implement the Angular-Spinner in my project: Specifically, I want to use it with http.get calls. This is what I have so far: Within controllers: $scope.loading = true; $http.get('js/data/test.json').success(function(resu ...