JavaScript Three.JS Shadows Unable to Render

As a newcomer to Three.js, I am thoroughly enjoying it but facing some difficulties with shadow maps. Despite researching extensively, I can't seem to make it work. Could someone please guide me in identifying my mistake?


    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);
    var cube = new THREE.Mesh(geometry, new THREE.MeshLambertMaterial( {color: 0x808080 } ));
    cube.castShadow = true;
    scene.add( cube );

    camera.position.y = 2;

    var directionalLight = new THREE.DirectionalLight( 0xffffff, 0.5 );
    directionalLight.position.set( 0, 10, 0 );
    directionalLight.castShadow = true;
    scene.add( directionalLight );

    var geo2 = new THREE.BoxGeometry(5,0.1,5);

    var floor = new THREE.Mesh(geo2, new THREE.MeshLambertMaterial( {color: 0x808080 } ));
    floor.position.y = -1;
    floor.receiveShadow = true;
    scene.add(floor);

    renderer.shadowMapEnabled = true;
    renderer.shadowMapType = THREE.PCFSoftShadowMap;


    var ambient = new THREE.AmbientLight( 0x111111 );
    directionalLight.shadowCameraVisible = true;
    scene.add( ambient );


    renderer.shadowCameraNear = 3;
    renderer.shadowCameraFar = camera.far;
    renderer.shadowCameraFov = 50;

    function animate() {
        camera.lookAt({x:0,y:0,z:0});
        var timer = Date.now() * 0.0002;
        camera.position.x = Math.cos(timer) * 5;
        camera.position.z = Math.sin(timer) * 5;
        requestAnimationFrame(animate);
        render();
    }

    function render() {
        cube.rotation.x += 0.1;
        cube.rotation.y += 0.1;

        renderer.render(scene, camera);
    }
    animate();

Answer №1

Make sure to adjust the following settings:

renderer.shadowCameraNear = 3;
renderer.shadowCameraFar = camera.far;
renderer.shadowCameraFov = 50;

Instead of placing these lines on the renderer, they should be applied to your light as shown below:

directionalLight.shadowCameraNear = 3;
directionalLight.shadowCameraFar = camera.far;
directionalLight.shadowCameraFov = 50;

Since the light is directional, ensure you set the following parameters:

directionalLight.shadowCameraLeft = -500;
directionalLight.shadowCameraRight = 500;
directionalLight.shadowCameraTop = 500;
directionalLight.shadowCameraBottom = -500;

Feel free to adjust these values to achieve the desired outcome.

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

The redirect feature in getServerSideProps may not function properly across all pages

Whenever a user visits any page without a token, I want them to be redirected to the /login page. In my _app.js file, I included the following code: export const getServerSideProps = async () => { return { props: {}, redirect: { des ...

What is the method for adding an event listener in AngularJS within an ng-repeat iteration?

I'm completely new to AngularJS and currently working on building a photo gallery. The basic idea is to have an initial page displaying thumbnail photos from Twitter and Instagram using an AngularJS ng-repeat loop. When a user hovers over an image, I ...

Encountering an issue when trying to send data with Axios client to the child component

I'm encountering an issue while attempting to pass data to a child component for rendering. import axios from 'axios'; import React from 'react'; import MovieCard from './MovieCard'; import { useState, useEffect } from ...

Development mode causing sluggish asset compilation

I am facing an issue with a large rails application that has hundreds of coffee script files. Whenever I make a small change in a coffee script file or switch branches, the entire assets need to be precompiled, causing a significant delay in loading the p ...

Trouble with AJAX Post Request: Missing JSON Response

Below is the AJAX request I have created: var data = modalDom.find("form").serializeObject(); data["returnJson"] = true; $.ajax({ type: "POST", url: "/companies/edit/", data: data, dataType: "JSON", success: function (result) { ...

JavaScript keeps repeating as you perform basic addition operations

Dealing with a similar issue where things are not adding up correctly, I encountered a problem in a previous question about JavaScript variables only concatenating as strings. The pure JavaScript solution worked fine, so I have now consolidated all the cod ...

PhoneGap/Cordova-built android application fails to display external links

I'm currently developing a geolocation app and encountering an issue with loading a Google map. The native geolocation is functioning properly, but incorporating the map has been challenging, similar to the example shown in Simple Markers here. After ...

Transform an array of objects into an object of objects while maintaining the interior structure

I am searching for a specific solution that I have not come across yet. If such a solution exists, I would greatly appreciate a link to it. Currently, my code looks like this: const obj = {"key": [ { "name": { "companyName": "Something" } }, { "otherT ...

Navigating back to the app after saving contacts can be achieved using React Native and the react-native-contacts library

I am currently utilizing the react-native-contacts library in my React Native application to save a contact. Prior to saving the contact, I request WRITE permission from Android. The process is successful; I open the contact form within my app and proce ...

Tips for accessing a value from a setInterval function

Is it possible to retrieve a value from the setinterval function in JavaScript? $.ajax({ type : "POST", url:"<?php echo TESTMINE_APP_URL; ?>/ajax/export-details", data:'paginationHash='+paginationHash+'&exp ...

Guide to running JavaScript in Selenium using JavaScript and retrieving the output

I am currently utilizing JavaScript with the selenium library selenium-webdriver. Below is my code snippet: var chromeCapabilities = webdriver.Capabilities.chrome(); this.driver = new webdriver.Builder() .forBrowser('chro ...

Implementing a function to load HTML pages upon clicking a button with JavaScript

I need help creating a button that loads an HTML page using JavaScript, without redirecting to the page. However, the current code I have is not loading the HTML page as desired. Here is the code snippet in question: <!DOCTYPE html> <html> &l ...

Unable to trigger ActionFunction with Remix and MUI slider

I am trying to implement a MUI slider in order to update a database by using Remix ActionFunction. The issue I am facing is that when the MUI slider is moved, it reloads the default function instead of calling the ActionFunction. How can I make it trigger ...

Integrating Project Tango with Ionic and/or Angular in a cutting-edge mobile application

I'm currently working on a mobile app project and I could use some advice. The majority of the app can be developed using angular.js (and possibly ionic) JavaScript technology. However, there is one aspect that requires integration with an API, specif ...

The addScript feature seems to be experiencing difficulties upon the initial website load

Currently, I am utilizing the jquery.flexslider plugin and it is performing well. However, I have a specific requirement where I do not want to load the plugin for screens that are smaller than 600px. After experimenting with various scripts, I have final ...

Are none of the page links clickable?

Currently, I am in the process of creating a portfolio website. This is my first attempt at coding HTML and CSS from scratch without the aid of a layout template. I've encountered an issue that has me stumped - the links within the container are not ...

Having trouble adding state values to an object

I have a specific state set up in my class: this.state = { inputValue: "", todos: [] } My issue lies within an arrow function where I am attempting to use setState to transfer the value of inputValue into todos. this.setState({ inputValue: & ...

Using webpack with the production parameter

Currently working on an Express+React application which utilizes webpack for bundling. During development, I have been using "webpack --watch", but as I prepare to deploy to production, I am interested in uglifying my JavaScript code. Unfortunately, the ...

jQuery auto-suggest feature failing to display search results

Just to clarify, I have very little experience with JS, so my understanding is limited. Fair warning :-) I'm currently working on an autocomplete menu that retrieves data from a webservice. This webservice will return various types of elements (such ...

Make sure that the parent element is only visible once all of its child elements have

As a newcomer to the world of react, I am facing some challenges. I have created a form in react which includes a dropdown. To ensure reusability across multiple pages, I decided to turn this dropdown into a component that is responsible for fetching all n ...