Shadows for directional light in three.js

http://jsfiddle.net/wp6E3/3/

var camera, scene, renderer;
var cubes = [];

init();
animate();

function init() {

    scene = new THREE.Scene();
    scene.add(new THREE.AmbientLight(0x212223));

    for (var i = 0; i < 10; i++) {
        var cubeGeometry = new THREE.CubeGeometry(1, 1.5, 1);
        var cubeMaterial = new THREE.MeshLambertMaterial({ color: 0x1ec876 });
        var cube = new THREE.Mesh(cubeGeometry, cubeMaterial);
        cube.position.set(i*1.2, 0, 0.5);
        cube.castShadow = true;
        scene.add(cube);

        cubes.push(cube);
    }

    camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 10000);
    camera.position.x = -4;
    camera.position.y = -4;
    camera.position.z = 20;
    camera.lookAt(cubes[5].position);
    scene.add(camera);

    var terrainGeo = new THREE.PlaneGeometry(50, 50);
    var terrainMaterial = new THREE.MeshLambertMaterial({ color: 0xc0c0a0 });
    var terrain = new THREE.Mesh(terrainGeo, terrainMaterial);
    terrain.receiveShadow = true;
    scene.add(terrain);

    var light = new THREE.DirectionalLight(0xffffff, 1);
    light.castShadow = true;
    light.shadowCameraVisible = true;
    light.position.set(-3, 1, 5);
    scene.add(light);
    scene.add( new THREE.DirectionalLightHelper(light, 0.2) );

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.shadowMapEnabled = true;
    renderer.shadowMapSoft = false;
    document.body.appendChild(renderer.domElement);
}

function animate() {
    requestAnimationFrame(animate);
    for (var i = 0; i < cubes.length; i++) {
        cubes[i].rotation.x += 0.01 * i;
        cubes[i].rotation.y += 0.02 * i;
    }

    renderer.render(scene, camera);
}

What am I missing with the shadows?

I've reviewed similar questions and read through Three.js documentation but cannot figure out my mistake.

Three.js shadows not working properly

How to create directional light shadow in Three.JS?

ThreeJS shadow not rendering

Answer №1

To begin, make sure to include a camera controller in your scene so you have a clear view of your work. This will allow you to adjust the camera for different perspectives.

controls = new THREE.OrbitControls( camera, renderer.domElement );

Next, if you are using jsfiddle, remember to reference the most recent version of the three.js library.

<script src="http://threejs.org/build/three.min.js"></script>

To ensure proper resolution, it's important that your shadow camera is placed closely around your scene. You can achieve this by setting the following parameters:

light.shadowCameraLeft = -20; // adjust as needed for your scene scale
light.shadowCameraRight = 20;
light.shadowCameraTop = 20;
light.shadowCameraBottom = -20;

When dealing with directional lights, the key factor is the "direction to" the light's position. However, when utilizing shadow maps, the actual position of the light becomes crucial as it influences the shadow camera.

light.position.set( -60, 20, 100 );

Here is an updated fiddle where you can manipulate the camera using your mouse:

http://jsfiddle.net/wp6E3/4/

three.js r.66

Answer №2

Include these in your explanation of illumination:

light.shadowMapWidth = 
light.shadowMapHeight = 1024;
light.shadowCameraNear = 1;
light.shadowCameraFar = 100;

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

Receiving the result as well as encountering undefined initially during AJAX request

I have a dropdown menu, and when a user selects an option, an AJAX call is made to retrieve and display data based on the selected value. If the dropdown value is 2, it triggers the AJAX request. However, I am encountering two issues: https://i.sstatic.n ...

Slider with Dual Images: A Visual Comparison

I'm currently working on a webpage that features before and after images using a slider based on mouse movement to display both pictures. I am trying to incorporate multiple sliders on the same page but have been facing difficulties in getting them to ...

Shuffle math calculations involving subtraction by a percentage using node.js or JavaScript

Hello there! If you want to subtract, say 35%, from a number, you can use methods like this: var valueInString = "2383"; var num = parseFloat(valueInString); var val = num - (num * .35); console.log(val); But have you ever wondered how you could randomiz ...

Unable to run the method in the parent component from the child component

I am attempting to trigger a method to run on a parent component when a button within one of its child components is clicked. I am utilizing single file components with Webpack. Below is the code for the child component: <template> <button v-on ...

Implementing NodeJS to showcase an array of items - the step-by-step guide

I'm currently setting up a webpage to display a list of books using NodeJS, but despite my efforts, the page remains blank when I launch it. My goal is to showcase the array of books on the page, and so far, here's the code that I have written. A ...

TypeError thrown by Basic TypeScript Class

I'm encountering an issue where TypeScript is throwing a TypeError when trying to use the class Literal from file Classes.tsx in file App.tsx, even though they are in the same file. Strangely, everything works fine on typescriptlang.org/play. // Class ...

Enforcing object keys in Typescript based on object values

I'm looking to design a structure where the keys of an object are based on values from other parts of the object. For example: type AreaChartData = { xAxis: string; yAxis: string; data: { [Key in AreaChartData['xAxis'] | AreaChart ...

Guide on transforming a select dropdown into a ul dropdown

I am attempting to transform my select dropdown menu into an unordered list (ul) in order to create a bootstrap button that will display the ul, allowing the list items to function as options. <select id="sortField" onchange="refreshPage('{$pageBa ...

D3 Treemap for handling extensive sets of data

I am uncertain if there exists a method to incorporate the desired feature. I am seeking a solution similar to zoomable treemaps, but to initially load a limited number of child levels and then dynamically add more child nodes without requiring a node clic ...

Firestore/Javascript error: FirebaseError - The data provided is invalid for the DocumentReference.set() function. An unsupported field value of 'undefined'

I keep encountering this error Error creating user: FirebaseError: Function DocumentReference.set() called with invalid data. Unsupported field value: undefined (found in field diabetesComplication) After some investigation, I realized that the iss ...

Having trouble interacting with Xpath elements using Selenium and Java?

I have been attempting to access a search bar and submit the query without a SEARCH BUTTON. While I was able to enter the search query using javascriptexecutor, I encountered difficulty when trying to perform an Enter button action as there was no actual E ...

Adjusting speed dynamically within a setInterval function in JavaScript

I am working on a react application that requires displaying text with varying intervals between sentences, one at a time. To achieve this functionality, I stored all the sentences in an array and implemented a setInterval function: startShowingText() ...

Next.js: Uh-oh! Looks like we've hit an obstacle with Error 413 Request Entity

I've encountered an issue while attempting to upload large files using Next.js. I've set up an onChange function for my file input, and here's the code snippet: const handleFileUpload = () => new Promise(async (resolve) => { if(ref ...

Displaying Grunt Command-Line Output in Browser

Is there a straightforward method to display the command-line output of a grunt task in a browser? Essentially, I want to showcase the input and/or output of a command line process within a browser window. While I am aware that I could develop a custom app ...

Is it possible to render a web page in C++ that includes JavaScript, dynamic html, and retrieve the generated DOM string?

Is there a way to fetch and extract the rendered DOM of a web page using C++? I'm not just talking about the basic HTTP response, but the actual DOM structure that is generated after JavaScript has executed (possibly after allowing it some time to run ...

Comparable user interface on par with what we find on Windows Phone 7

I'm quite impressed with the innovative interface experience of Windows Phone 7. It stands out compared to other interfaces, whether on mobile devices, desktops, or the web. Despite its uniqueness, it remains highly usable. Overall, a great step in th ...

Encountered an Unhandled Rejection error in React due to SyntaxError: Unexpected token '<' found in JSON at position

Every time I attempt to access the global variable from a different component, specifically when I try to use it from Brewery.js in Random.js, I encounter the "Unhandled Rejection (SyntaxError): Unexpected token < in JSON at position 0" error. Brewery. ...

Mesh color remains unchanged when the mouse hovers over it

I want to create a cool effect where the color of a mesh changes when the mouse hovers over it and returns to its original color when the mouse moves away. Here is my attempt: init(); animate(); //calling function that does all the rendering //GLOBAL ...

Typescript allows you to apply a filter to an array

Query: Is there a way to display a pre-selected item from my dropdown using its unique ID? Issue/Explanation: The dropdown options in my web service are dynamically fetched based on a user's ZipCode. For example, a Provider is displayed as {Pho ...

Sort through the JSON data and showcase it in a gridded format

I need assistance with displaying data from a JSON object in a grid based on user selections. The user should be able to select a year and make from a dropdown menu, and the corresponding data should then be filtered and displayed in a grid. For example, i ...