I attempted to consolidate all the necessary functionalities into a single class to create a straightforward three.js scene with a cube. Despite not encountering any errors, the scene remains black when viewed in the browser. Here is the code I've written:
class SceneInitialization {
constructor(fov = 45,camera,scene,controls,renderer)
{
this.camera = camera;
this.scene = scene;
this.controls = controls;
this.renderer = renderer;
this.fov = fov;
}
initScene() {
this.camera = new THREE.PerspectiveCamera(this.fov, window.innerWidth / window.innerHeight, 1, 1000);
this.camera.position.z = 15;
this.controls = new THREE.TrackballControls( this.camera );
this.scene = new THREE.Scene();
this.renderer = new THREE.WebGLRenderer({canvas: document.getElementById('myThreeJsCanvas') , antialias: true});
this.renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(this.renderer.domElement);
let ambientLight = new THREE.AmbientLight(0xffffff, 0.7);
ambientLight.castShadow = false;
this.scene.add(ambientLight);
let spotLight = new THREE.SpotLight(0xffffff, 0.55);
spotLight.castShadow = true;
spotLight.position.set(0,40,10);
this.scene.add(spotLight);
window.addEventListener('resize', this.onWindowResize, false);
}
animate(){
requestAnimationFrame( this.animate.bind(this) );
this.render();
this.controls.update();
}
render(){
this.renderer.render( this.scene, this.camera );
}
onWindowResize() {
this.camera.aspect = window.innerWidth / window.innerHeight;
this.camera.updateProjectionMatrix();
this.renderer.setSize( window.innerWidth, window.innerHeight );
}
}
Afterwards, I instantiate a new object and add an item to the scene. Although inspecting the scene's children returns the expected objects, the scene itself still shows up as black. Only the renderer window displays in the browser.
let myScene = new SceneInitialization(45);
myScene.initScene();
myScene.animate();
let geometry = new THREE.BoxBufferGeometry(200, 200, 200);
let material = new THREE.MeshBasicMaterial();
let mesh = new THREE.Mesh(geometry, material);
myScene.scene.add(mesh);
console.log(myScene.scene.children); //returns 3 objects (ambientLight, spotLight, mesh)