How come the light effect isn't displaying in my three.js code?

I followed the instructions in the manual to create a three.js example, but I'm having an issue where the light effect is not appearing. Even though there are no errors related to the light source, it's still not showing up. Can anyone help me understand why this is happening?

import * as THREE from "/assets/threejs/build/three.module.js"

class App {
    // Initialization
    constructor(){
        const divContainer = document.querySelector("#webgl-container");
        this._divContainer = divContainer;

        const renderer = new THREE.WebGLRenderer({antialias: true})
        renderer.setPixelRatio(window.devicePixelRatio);
        divContainer.appendChild(renderer.domElement);
        this._renderer = renderer;

        const scene = new THREE.Scene();
        this._scene = scene;

        this._setupCamera();
        this._setupLight();
        this._setupModel();

        window.onresize = this.resize.bind(this);
        this.resize();

        requestAnimationFrame(this.render.bind(this));
    }
    
    // Camera setup
    _setupCamera() {
        const width = this._divContainer.clientWidth;
        const height = this._divContainer.clientHeight;
        const camera = new THREE.PerspectiveCamera(
            75,
            width / height,
            0.1,
            100,
        )
        camera.position.z = 2
        this._camera = camera;
    }

    // Light setup
    _setupLight(){
        const color = 0xffffff;
        const intensity = 1;
        const light = new THREE.DirectionalLight(color, intensity);
        light.position.set(-1, 2, 4);
        this._scene.add(light);
    }

    // Model setup
    _setupModel(){
        const geometry = new THREE.BoxGeometry(1,1,1);
        const material = new THREE.MeshBasicMaterial( { color: 0x44a88 } );
        const cube = new THREE.Mesh( geometry, material );
        this._scene.add(cube);
        this._cube = cube;
    }
 
    // Resize window
    resize(){
        const width = this._divContainer.clientWidth;
        const height = this._divContainer.clientHeight;

        this._camera.aspect = width / height;
        this._camera.updateProjectionMatrix();

        this._renderer.setSize(width, height);
    }

    // Rendering
    render(time){
        this._renderer.render(this._scene, this._camera);
        this.update(time);
        requestAnimationFrame(this.render.bind(this));
    }

    // Update function
    update(time){
        time *= 0.001;
        this._cube.rotation.x = time;
        this._cube.rotation.y = time;
    }

}

window.onload = function(){
    new App(); 
}

The screenshot below shows the result of my example code. https://i.sstatic.net/hzreM.png

The screenshot below displays the result from the manual. https://i.sstatic.net/4NTMd.png

I apologize for asking multiple questions about a seemingly simple problem, but I am new to learning three.js. I am finding it difficult without proper code hints in vscode. Can someone guide me on how to properly showcase the light effect in my example code? Is there something that I may be missing? Thanks for taking the time to read and assist with this issue.

Answer №1

Avoid using MeshBasicMaterial, instead opt for MeshStandardMaterial. While MeshBasicMaterial is suitable for creating flat or wireframe geometries, MeshStandardMaterial offers a physically realistic appearance with light interactions on the surface.

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

Introduction to Interactive HTML Pinball Game

As a beginner in the realm of computer science, I've recently embarked on creating a simple pinball game. My approach to maneuvering the flippers involves switching between images that depict the flipper in an upwards and downwards position by utilizi ...

Transform a section of a canvas into a PNG file

I am in the process of converting my html5 canvas into a png format using this code snippet: var canvas = document.getElementById("mycanvas"); var img = canvas.toDataURL("image/png"); document.write('<img src="'+img+'"/>'); I ...

What is the syntax for creating a zip function in TypeScript?

If I am looking to create a zip function: function zip(arrays){ // assume more than 1 array is given and all arrays // share the same length const len = arrays[0].length; const toReturn = new Array(len); for (let i = 0; i < len; i+ ...

The Bootstrap 3.3 Carousel is stationary and does not rotate

I am facing a challenge with implementing a Carousel using Bootstrap version 3.3.7 on my website. The code snippet is as follows: <!-- Carousel ================================================== --> <div class="row dark-start d-none d-lg-block"&g ...

Creating visually appealing doughnut charts with rounded borders by utilizing multiple datasets in ChartJs

Currently, I am working on a Chartjs doughnut chart with multiple datasets. Here is the code snippet for the datasets: datasets: [ { label: 'Bugs', data: [ 60 , 6.6666666666667 , 33.333333333333 ], ...

Sorting through an array using several filter arrays

Is there a way to efficiently filter an array of items based on multiple filter arrays? Each item has various filters, and I want to display only the ones that match all selected filters. const selectedFilters = { color: ["Red", "Blue"], type: ["S ...

Reactjs is displaying an AxiosError stating a Network Error

Working on a project with Reactjs and Nextjs, I encountered an issue where the data being posted with axios is inserting "NULL" values. I'm not sure where I am going wrong. Below is the code snippet in Nextjs: const userData = { name: state.name, ...

What is the reason behind this error: Error: connect ECONNREFUSED?

I am facing an issue while trying to establish a connection with the Mailchimp API. The error occurs when I run the app.js file. import mailchimp from "@mailchimp/mailchimp_marketing"; mailchimp.setConfig({ apiKey: "apiKey", server ...

Having trouble getting the Node.JS Express Server to function properly on Enide?

My webserver is built using Node.JS with express and has multiple route commands. While everything works fine when running Node from the command line, I encounter an issue when running it within the Enide environment. Each request triggers an error messa ...

Running the npm install command will eliminate any external JS or CSS files that are being

For my project, I incorporated jquery-datatimepicker by including jquery.datetimepicker.min.css and jquery.datetimepicker.full.min.js in angular.json and placed them within the node_modules/datetimepick directory. Here is a snippet of my angular.json conf ...

Can the Angular link function activate the change event?

I am facing an issue with my Angular directive that includes a link function. Inside this function, I am initializing a jQuery plugin which can be seen in action here: https://plnkr.co/edit/58nOhypt6FRdI4At5jwu. The problem arises when every time the dire ...

What is the process for assigning a regular expression to an object?

As I work on editing a configuration file, I'm encountering some issues where things aren't quite functioning as expected. Below is the code snippet I am working with: config.module.rules.unshift( { test: "/ckeditor5-[^/\\ ...

What is the best way to send a form using ajax?

I am having trouble submitting forms without a post back using AJAX. My code is not working as expected. What could be the issue in my script? I am new to AJAX and would appreciate some help with AJAX scripts. Below you can find my code: Please note: I ...

Can Selenium in JavaScript be used to retrieve child elements from a webpage?

I've been struggling to adapt my JavaScript script for use with Selenium (also in JavaScript). Despite numerous attempts, I haven't been able to find a solution. I've attached an image to better explain my question await chromeDriver.findEle ...

Immersive jQuery slideshow embellished with an interactive counter, captivating thumbnails, dynamic progress bar,

Hey there! I'm currently working on my very first website and I could really use some assistance in creating a slider with images. I've tried searching for a solution to my problem online, but even after attempting to fix the suggested plugin, I ...

javascriptconst eventEmitter = require('events').EventEmitter;

Have you ever wondered why certain code snippets work while others don't? Take for example: var EventEmitter = require('events').EventEmitter; var channel = new EventEmitter(); this code works perfectly fine, but when we try something like ...

Acquire the current audio video stream directly from the web browser

Currently, I am utilizing a JavaScript library that internally invokes getUserMedia. My objective is to access the stream object that has already been initiated. Unfortunately, the library does not provide any means to retrieve it. Is there a method avai ...

Having trouble resolving a setInterval problem with JavaScript?

Yesterday, I learned about the setInterval function which allows me to execute a task or function after a specific amount of time. While I have successfully implemented the interval in my code, it keeps adding new lines with the date each time. What I re ...

Issues arise when attempting to use custom Javascript functions in conjunction with the Bootstrap 4 Input Tagging Plugin

Currently, I am utilizing the Bootstrap tags input plugin to create tags within a text input on my HTML page. However, I am encountering difficulties in executing Javascript functions that should be activated when the input field is clicked while using thi ...

Exploring ways to repeatedly collapse rows using HTML, CSS, and JavaScript

GOAL: I want to freeze the header, freeze the first column, and be able to collapse rows multiple times. CURRENT PROGRESS: I have achieved freezing the header, first column, but can only collapse rows once. MY CODE SNIPPET: </head> <body> &l ...