What is preventing the THREE.Mesh constructor from accepting an array of Materials as an argument in this case?

I'm completely new to three.js and I'm having trouble understanding why the array isn't working in this scenario. After reading through the documentation and several tutorials, it seems that passing an array to the constructor is the recommended approach.

According to threejs.org:

Constructor

Mesh( geometry : BufferGeometry, material : Material )

geometry — (optional) should be an instance of BufferGeometry. If not provided, a new BufferGeometry is created.
material — (optional) can either be a single Material or an array of Materials. Default value is a new MeshBasicMaterial

While I can successfully reference an index within the array to load the texture correctly:

// this works:
var cube = new THREE.Mesh( geometry, materials[4] );

// however, passing in the array directly doesn't work - what am I missing?
var cube = new THREE.Mesh( geometry, materials );

I have created a Codepen demo here. with the same code as shown below:


function make_texture(name)
{
  const ctx = document.createElement('canvas').getContext('2d');
  document.body.appendChild(ctx.canvas);
  ctx.canvas.width = 256; ctx.canvas.height = 256;
  ctx.font = '20pt Arial';
  ctx.fillStyle = 'red';
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
  ctx.fillStyle = 'white';
  ctx.fillRect(5, 5, ctx.canvas.width - 10, ctx.canvas.height - 10);
  ctx.fillStyle = 'black';
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  ctx.fillText(name, ctx.canvas.width / 2, ctx.canvas.height / 2);
  const texture = new THREE.CanvasTexture(ctx.canvas);
  return texture
};

var materials = [];
for ( var i = 1; i < 7; i ++ ) {
    materials.push( new THREE.MeshBasicMaterial( { map: make_texture(i) } ) );
};

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );

var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

var geometry = new THREE.BoxGeometry( 1, 1, 1 );

// this works:
// var cube = new THREE.Mesh( geometry, materials[4] );

// passing in the array directly doesn't work - what could be causing the issue?
var cube = new THREE.Mesh( geometry, materials );


scene.add( cube );

camera.position.z = 3;

var pointLight = new THREE.PointLight(0xffffff, 1.5);
pointLight.position.set(0, 300, 200);

scene.add(pointLight);

var animate = function () {
  requestAnimationFrame( animate );

  cube.rotation.x += 0.01;
  cube.rotation.y += 0.01;

  renderer.render( scene, camera );
};

animate();

Answer №1

Upon further investigation, it was determined that the issue stemmed from a versioning problem. Specifically, the template I utilized on CodePen included a revision of three.js from the CDN labeled as r84, which resulted in the described behavior.

By adjusting the settings in the CodePen to utilize r128 instead, using the provided links here, the issue was resolved and the functionality returned to normal.

The corrected CodePen can be found here.

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

Scrollbar auto-scrolling problem

I have been attempting to create a div that displays content scrolling horizontally, similar to a slideshow, after a set period of time. I am utilizing the mcustomscrollbar plugin in my implementation. As I iterate through a for loop to increment the IDs a ...

Decoding various JSON arrays received through AJAX requests

After returning two objects as JSON through AJAX, I am facing an issue with accessing the values in these two lists. Previously, when I had only one list, I could parse it easily. data = serialize("json", vm_obj) data2 = serialize("json", user_networks_li ...

Updating React JSX class based on certain conditions without manipulating the actual DOM

When working with jsx react, I am looking to dynamically set a class while keeping another class static. Here is an example of what I would like to achieve: maintaining the type class and having an additional dynamic class change change to either big, smal ...

Difficulty accessing PHP information in an external file when using getJSON

In my wos.php file, I have created an array that is then encoded using json_encode and echoed to be used in another file named data.php through jQuery. However, the data is not being received as expected. Here is an example of the array ($recordArray) cre ...

Explore the functionality of the router replacement feature in Next.js

Currently, I am in the process of learning Next.js, but unfortunately encountered an error. import { useRouter } from "next/router"; export default function Auth() { const router = useRouter(); const root = router.query.auth; if (root !== ...

The best way to efficiently search a JavaScript object or an array of objects is by utilizing the most

In my JavaScript code, I am working with an array of objects like this: var arrayObjs = [ { id:abc123, radius:5.0}, { id:def235, radius:2.5},...] I have been using a for loop to search for a specific object with the id 'def235'. I'm curiou ...

Spicing up javascript with Currie's arrow function

Can you please break down this function in a straightforward way (without using arrows)? I'm having trouble understanding if "foo" in Promise.resolve "foo" is an argument or a callback function. module.exports = function foo(req, res, next) { retu ...

Encountering an error in Node JS while attempting to utilize the Formidable package

I am currently studying the Node.js Comprehensive Guide textbook. Encountered an issue while trying to utilize the "Formidable" package for handling form uploads, triggering an error const form = new formidable.IncomingForm(); ^ Type ...

Using Regular Expressions in JavaScript for Filtering with Angular.js

I am looking to create a custom filter in Angular.js. When an object has a name == null, and I add "u" to the filter->, it results in the return of the object where name == null because re.test(null)=true. However, other characters are returning false. ...

In the provided Javascript snippet, how would you classify `word` - a function, variable, or object?

Understanding that an object is a variable and a function is a type of object, I find myself confused about the proper way to reference word in the following code snippet: var word; exports.setWord = function(c, ch){ word = c.get('chats')[ch]; ...

Utilize the synchronization feature of ES6 Promises in Jasmine with the then/catch method

I have an angular controller that needs to be tested. This controller utilizes a service to fetch data from a server, and the service returns ES6 Promises. function MyController($scope, MyService) { $scope.doSomething = function () { MyService.foo() ...

Webhost sending information to Windows sidebar gadget

Is there a way to showcase a list of information from a web host on a Windows sidebar gadget without using iframes? I've heard about using JavaScript AJAX (XmlHttpRequest) for this purpose, along with a refreshing function. Can anyone provide some gui ...

Is there a way to remove a particular map from Firestore?

In my Google Firebase setup, I have uniquely named each Map to serve as the index for every document. Using Vuejs (Javascript), I have structured it as follows: eQFelbD432T (Collection Name- user.uid) SKILLS (Document Name) ProjectManangement (Map Na ...

Is there a way to implement tooltips on an element that has text-ellipsis enabled?

I am facing an issue with displaying an account number that exceeds 100 characters. I need to restrict the display with overflow hidden while still being able to show the full account number using a tooltip. Below is the code snippet: <span class="tex ...

Utilizing Angular and TypeScript: The best approach for managing this situation

I need some guidance on handling asynchronous calls in Angular. Currently, I am invoking two methods from a service in a controller to fetch an object called "categoryInfo." How can I ensure that these methods return the categoryInfo correctly and displa ...

JWT - Effective strategies for enhancing the user experience for a returning logged-in user

My client authentication system involves storing a JWT in `localStorage` once the user is verified. However, I'm not satisfied with the current user experience when a returning user is redirected straight to a new page without warning. window.locatio ...

Issues arise with tabbed content as default content fails to display and classes are not added upon clicking

I'm currently working on a tabbed module that consists of three tabs. Here's how it operates: When the user clicks on a carousel_element, it reveals carousel_hidden-text within that div and displays it in another div called carousel_quote. I&ap ...

Generate a novel item by organizing the key of an array of objects

I have an array of objects containing various items: [ { CATEGORY:"Fruits" ITEM_AVAIL:true ITEM_NAME:"Apple" ITEM_PRICE:100 ITEM_UNIT:"per_kg" ITEM_UPDATED:Object ORDER_COUNT:0 }, { CATEG ...

PHP script encountering server error due to JavaScript file upload

I've been going crazy for the past month trying to create a page that can asynchronously submit a PDF to our server. Although I have experience in programming, I have never ventured into web development, PHP, or JavaScript before. Here is the JavaScr ...

Creating sequential hover animations with CSS in HTML

I have a total of four divs that I want to hover continuously, one after the other. Here is the code I am currently using: #rij1 .content-overlayz, #rij1 .content-details { animation-duration: 2s; animation-name: stepped-pulse; animation-iterati ...