Unable to visualize object in three.js

Looking to generate cubes in a random location on the page using a for loop, but currently experiencing issues where the cubes are not appearing as expected.

**Note: When I check the cube with console log, this is the output: **

-cube.js:24 Mesh {uuid: "8859E918-7D3A-47ED-BDEF-072BC60FF725", name: "", type: "Mesh", parent: Scene, children: Array(0), ...}

  
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth / 
window.innerHeight, 0.1, 1000 )
camera.position.z = 5;
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
window.addEventListener('resize', () => {
  renderer.setSize(window.innerWidth,window.innerHeight);
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
})

var geometry = new THREE.BoxGeometry(3, 1, 1);
var material = new THREE.MeshLambertMaterial({color: 0x00ff00});
var cube = new THREE.Mesh(geometry, material);
meshX = -5;
for(var i = 0; i<20;i++) { //amount of shapes
  cube.position.x = (Math.random() - 0.5) * 10; //Location of shapes
  cube.position.y = (Math.random() - 0.5) * 10;
  cube.position.z = (Math.random() - 1.2) * 10;
  scene.add(cube);
  meshX+=1;
  console.log(cube);
}

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

Answer №1

To use a light with MeshLambertMaterial (as opposed to MeshBasicMaterial which does not require lights), ensure that you create a new Cube instance within the loop instead of just changing the initial cube's location.

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / 
  window.innerHeight, 0.1, 1000)
    camera.position.z = 5;
var renderer = new THREE.WebGLRenderer({antialias: true});
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
window.addEventListener('resize', () => {
  renderer.setSize(window.innerWidth, window.innerHeight);
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
})

// Create ambient light and add it to the scene.
var light = new THREE.AmbientLight(0x404040); // soft white light
scene.add(light);

var geometry = new THREE.BoxGeometry(3, 1, 1);
var material = new THREE.MeshLambertMaterial({color: 0x00ff00});
//var cube = new THREE.Mesh(geometry, material);
//meshX = -5;
for (var i = 0; i < 20; i++) { //amount of shapes
  var cube = new THREE.Mesh(geometry, material);
  cube.position.x = (Math.random() - 0.5) * 10; //Location of shapes
  cube.position.y = (Math.random() - 0.5) * 10;
  cube.position.z = (Math.random() - 1.2) * 10;
  scene.add(cube);
  //meshX+=1;
  //console.log(cube);
}

var render = function() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
 render();
body {
  padding: 0;
  margin: 0;
  position: relative;
}
<script src="https://rawgithub.com/mrdoob/three.js/r104/build/three.js"></script>

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 effective method to prevent postback controls from activating before the page is fully loaded?

My website contains high-quality graphics, which may lead to slow download times for users with poor internet connections. As the browser is still loading, users often access form options and submit their information prematurely. This premature submission ...

What is the best way to transform a date such as '2021-06-01T11:17:00-07:00' into the corresponding date and time for a specific location (New Delhi) using JavaScript?

How can I convert a date in the format '2021-06-01T11:17:00-07:00' to ISO standard? What does this format represent? let date = new Date('2021-06-01T11:17:00-07:00'); console.log(date.getHours() + " :" + date.getMinutes()); I ...

Is your event listener failing to activate?

I have been working on a project where I gather array elements from user input and try to display them in an HTML table. Unfortunately, the event listener seems to not be triggering, and I can't figure out why. Here is the relevant HTML code: ...

Encountering an issue with Angular 5.2 application build on VSTS build server: Running into "CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory" error

Out of nowhere, the builds began failing with the following error : 2019-01-03T12:57:22.2223175Z EXEC : FATAL error : CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory error MSB3073: The command "node node_modules/webpack/bin/w ...

"Encountering a 400 Error While Attempting to Edit Requests in NodeJS/A

Currently, I am building an application using Ionic/Angular with a NodeJS backend. Within this project, I have created an update form that allows users to modify or delete a specific row. While the deletion function is working fine, I am facing some challe ...

I am encountering the ERR_STREAM_WRITE_AFTER_END error in my Node.js API. Does anyone know how to resolve this problem?

When I try to upload a file using the API from the UI, I encounter the following issue. I am interacting with a Node.js API from React.js and then making calls to a public API from the Node.js server. https://i.stack.imgur.com/2th8H.png Node version: 10. ...

Assign the value of one dropdown menu based on the selected value of another dropdown menu using PHP

When a selection is made in the first dropdown, I want the values in another dropdown to be populated accordingly. I need to verify the value of the first dropdown with a variable and then populate the options in the second dropdown based on that conditio ...

Restrict date range in Bootstrap Datepicker based on database values

Is there a way to remove specific date ranges from the database? For instance, if I have date ranges from 15.01.2021 to 21.01.2021 and from 24.01.2021 to 03.02.2021, is it possible to prevent these dates from being selected in the datepicker? I would lik ...

Incorporate a different address using $location.path(path); and submit the ng-form

I have a form: <form name="myForm" ng-submit="save(myObject)"> ... <button type="submit" class="btn btn-primary" ng-click="changeLocation('/railway-connection')">Save </button> </form> My goal is to perform two actions w ...

Learn how to calculate and showcase time discrepancies in minutes using Angular2

I am currently working on an Angular app that displays orders using the *ngFor directive. Each order has a datetime field indicating the date it was created. My goal is to implement a timer that shows how long a customer has been waiting for their order ...

JavaScript regular expression for detecting valid currency values

I am encountering an issue with removing decimal values from a monetary amount retrieved from a JSON feed: For example, if I have: 150,000, I want to display it as just 150 Here is the code snippet I am using: $.getJSON('/static/js/datatest.json&ap ...

Is there a way to prevent jQuery.ajax() from displaying errors in the console?

I have set up a jQuery JSONP request to monitor the status of a resource based on its URL. In case the resource is not accessible or the server goes down, my ajaxFail() function takes care of updating the display. function fetchServerStatus(service, host) ...

One way to position a sidebar between two divs is to ensure it adjusts seamlessly to the size of the browser window when resized

In my layout, I have two grids: one for the header and one for the footer. In between these two grids, I am using a sidebar on the left side. Below is the JavaScript code I am using: function adjustSize() { var heights = window.innerHeight; docum ...

What makes NPM thrive while submodules struggle with construction?

My experience with utilizing npm has often involved encountering seemingly meaningless errors - such as Visual Studio projects failing to build and build tools (e.g. python.exe / CL.exe) being unavailable on the command line. For instance, some packages t ...

Ensure the validation of multiple form fields in a single function

I've implemented code to validate a form field as you input values, changing the border color to red if invalid or green if valid: function FormValidation(){ var fn=document.getElementById("firstName").value; if(fn == ""){ document.ge ...

The Javascript function call from the <img src="myFunction()"> is malfunctioning

I am looking to dynamically pass the URL of an image using a JavaScript function. <head> <script> function myFunction() { var str1 = "somepictureurl.png"; return str1; } </script> </head> <body> <img src="myFu ...

The Node.js Express undefined callback function is causing issues

I'm currently working on a personal project and I don't have much experience with nodeJS. My goal is to retrieve remote JSON data, generate statistics based on that data, and display it. However, I am encountering some issues with the callback fu ...

Is there a way to incorporate jQuery validation similar to MVC data annotation?

In my MVC project, I have a master/details view page. The Details section is actually a partial view containing input fields and a save button displayed below. <button type="button" id="btnAddDetails" class="btn btn-primary">Add Details <span cl ...

automatically created button, form control named 'answer' that is not valid

Struggling with a challenge in attaching an event to a dynamically generated button. Despite conducting some research, most of the solutions suggest that this issue is typically related to a form control. However, in my scenario, the error "invalid form co ...

D3 group of legendary elements

Is there a way to group both the circle and text elements for each legend item together? I'm currently facing a challenge with the enter/exit methods. While I can create the groups (g), I'm unable to append the text and circle elements. li.sel ...