A class with Three.js

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)

Answer №1

Success! I have found the solution.

The issue in the code stemmed from the BoxGeometry being oversized, causing the camera to be located inside the box. With the clipping set to 1, the object was not rendering properly. To resolve this problem, one can either adjust the size of the BoxGeometry to be smaller or move the camera further away!

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

When using the <Routes> component, it will not render a component that acts as a container for multiple <Route> elements

Upon wrapping my component in <Routes>, I encountered this warning: Warning: [Categories] is not a <Route> component. All component children of <Routes> must be a <Route> or <React.Fragment> In App.js: const App = () => ...

I'm curious why my background generator is only altering a portion of the background instead of the entire thing

I've been attempting to create a JavaScript random background changer, but I'm encountering some challenges. The main issue is that instead of changing the entire page's background, it only alters a strip of it. Additionally, I'm curiou ...

In node.js, there is no function called file.open for reading files

I'm trying to access a local text file (not through the web) in order to parse it into an array. However, I am encountering an error that says: "file.open is not a function" var app = require('express')(); var http = require('http&apos ...

Adding multiple text as label and sublabel in a React MUI Tooltip can be achieved by utilizing the appropriate

I'm struggling to incorporate a MaterialUI Tooltip into my React application with two separate text lines. The first line should serve as the main title, while the second line functions as a sublabel. In this screenshot provided, you can see where I ...

a single button with dual functionalities

I am new to the development field and have a question about jQuery. I want a single button to perform two different actions. For example, let's say we have a button labeled Pause/Resume. When I click on the button, it should first display "Pause", and ...

Sync issues observed with jQuery slide animations

I am currently utilizing a carousel slider that includes text content. When the user clicks on the 'next' button, the .carousel-text div slides up to hide the text, the carousel then moves to the next slide, and finally the .carousel-text on the ...

"Easily toggle the visibility of values in checkboxes and organize them into groups with the power of JavaScript

Hey there! I am currently working on a project that involves grouping checkboxes and hiding/unhiding their content based on user interaction. Essentially, when the page first loads, the "All CARS" checkbox will be checked by default. If I then check the "C ...

The map function will produce a result of -1 when utilizing the $stateParams parameter

When attempting to pass a variable to a page, the URL I'm using is: http://localhost/project/#/app/intro/1 After routing to my controller, everything seems fine until I try to use the map function on an array in my controller - that's where the ...

Occasionally, the system may mistakenly flag a password as invalid even though it is indeed correct

To ensure the password meets certain criteria, it must start with a Z, have at least 8 characters, and contain an asterisk *. Take a look at this validating function: function validatePassword() { var strPassword; //Prompt user to enter pas ...

Restricting JQuery pop-up to be shown only once

I'm looking for a solution to have a pop-up appear only once when the mouse leaves the screen. I'm not very experienced with coding, so I'm struggling to figure out how to achieve this. // Implementing Exit Intent function addEvent(obj, ev ...

iterating over a nested map within a map in an Angular application

I wrote a Java service that returns an observable map<k, map<k,v>> and I'm currently struggling to iterate through the outer map using foreach loop. [...] .then( (response: Package) => { response.activityMap.forEach((key: s ...

Javascript: Issue encountered while the page was loading

Whenever I make an API call, an error keeps popping up every time the page loads. I can't seem to figure out why it's happening. Can anyone shed some light on this? I've tried to include the link: https://i.stack.imgur.com/3Ul0S.png This ...

Switch Bootstrap Tab

I have successfully implemented a bootstrap tab on my webpage and it is functioning as intended. Now, I am interested in adding an additional feature to the tabs. My question is, is it possible to toggle the content area if the same tab is clicked again? ...

Is it possible for me to automatically send the user's email and username through code without requiring any information from them while using the tawk.to chat widget?

I need assistance with automatically sending the user's email and name when they open a chat window. I have tried various methods to pre-fill the form data but it still appears empty. Please let me know if there is something I am missing. Thank you ta ...

Guide to Sending JSON Data using ASP.NET and jQuery

I'm trying to figure out how to return JSON data in my code. JavaScript $(function () { $.ajax({ type: "POST", url: "Default.aspx/GetProducts", data: "{}", contentType: "application/j ...

Using Firebase with Arrays in Javascript

Currently, my team and I are working on a project using Firebase with Vue.js as the framework. We've come across a challenge regarding creating, updating, and deleting elements in a Firebase cloud document. For instance, within our 'people&apos ...

Refusing to handle HTTP requests in Node and Express API for MongoDB interactions

I am currently in the process of creating a basic API for performing CRUD operations on a local mongo database. Despite having what seems like correct code, the CRUD operations result in pending requests that never seem to complete. Below are snippets of ...

Tips for transforming an Observable stream into an Observable Array

My goal is to fetch a list of dogs from a database and return it as an Observable<Dog[]>. However, whenever I attempt to convert the incoming stream to an array by using toArray() or any other method, no data is returned when calling the retrieveDo ...

How can I prevent an outside click event from triggering if it occurs on the button? (Using Vue 3)

Seeking assistance from anyone who can help me out. I have a popup and a button, and when I click the button, the popup window should open. Additionally, when I click outside the popup or on the button, the popup should hide. https://i.sstatic.net/vDZ7L.p ...

Is it possible for a component to have multiple templates that can be switched based on a parameter?

Scenario My task is to develop a component that fetches content from a database and displays it on the page. There needs to be two components working together to create a single page, following a specific component tree structure. DataList - receives ful ...