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();