Create a circle-shaped floor in THREE.JS that mimics the appearance of a shadow

I am working on creating a circle mesh with a gradient material that resembles a shadow effect. Specifically, I want the circle to have a black center and fade to almost white at the edges.

Currently, I have been able to create a circle and position it correctly using the following code snippet:

var floorGeometry = new THREE.CircleGeometry((Math.max(loadedObjectRotatedLength.x, loadedObjectRotatedLength.y)/2) + 15, 32);
var floorMaterial = new THREE.MeshBasicMaterial({color: 0xf0f0f0});

var floor = new THREE.Mesh(floorGeometry, floorMaterial);
floor.position = new THREE.Vector3((loadedObjectBoundingBox.min.x + loadedObjectBoundingBox.max.x)/2, (loadedObjectBoundingBox.min.y + loadedObjectBoundingBox.max.y)/2, loadedObjectBoundingBox.min.z);

However, I am struggling to create a material that mimics a Radial Gradient effect. Can anyone provide guidance or assistance with this? :/

Answer №1

There are multiple approaches to achieve this.

1) Utilizing a gradient image and applying it to the material, as suggested by @GuyGood in the comments

The code implementation would look similar to this:

    var circleGeometry = new THREE.CircleGeometry(200, 200, 32);
    var texture = THREE.ImageUtils.loadTexture('image/shadow.png');// replace with appropriate URL
    texture.anisotropy = renderer.getMaxAnisotropy();
    var material = new THREE.MeshBasicMaterial({
        map: texture,
        color:0xFFFFFF
    });
    mesh = new THREE.Mesh(circleGeometry, material);
    scene.add(mesh); 

2) Another method worth mentioning involves creating a canvas element where you can draw any shape (in this case, a circle with a gradient) and then convert it into a texture to apply onto the material.

The code for this approach will be like so:

 var circleGeometry = new THREE.CircleGeometry(100, 100, 100);
    // create a texture on canvas and apply it on material
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');

    var x = 150,
        y = 75,
        innerRadius = 0,
        outerRadius = 200,
        radius = 200;

    var gradient = ctx.createRadialGradient(x, y, innerRadius, x, y, outerRadius);
    gradient.addColorStop(0, 'black');
    gradient.addColorStop(1, 'white');

    ctx.arc(x, y, radius, 0, 2 * Math.PI);

    ctx.fillStyle = gradient;
    ctx.fill();

    var shadowTexture = new THREE.Texture(canvas);
    shadowTexture.needsUpdate = true;

    var material = new THREE.MeshBasicMaterial({
        map: shadowTexture,
        side: THREE.DoubleSide
    });

    mesh = new THREE.Mesh(circleGeometry, material);
    scene.add(mesh); 

JSfiddle showcasing implementation of method 2

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

React Next.js failing to trigger useEffect hook on live application

Recently, in my Next.js/React application, some previously functional pages began to exhibit strange behavior. Specifically, certain Axios requests within a useEffect hook are no longer being sent at all. Additional Information: The problematic file is a ...

Verifying the existing user in a personalized Ajax form that is used to update a Woocommerce order

Currently, I am developing a form that allows users to update specific order details, such as expenses and the reason for the expense. After updating the order, a JavaScript alert confirms the successful update, and the order's metadata is updated acc ...

What is the inner workings of stream.Transform in Node.js?

Recently, I stumbled upon a code snippet on a blog showcasing the usage of the stream Transform class to modify data streams and display the altered output. However, there are certain aspects of this code that leave me puzzled. var stream = require(&apos ...

Create a chronological timeline based on data from a JSON object

Here is a JSON object generated by the backend: { "step1": { "approved": true, "approvalTime": "10-11-2021", "title": "title 1", "description": "description 1" ...

Eliminate list items with a keyboard stroke

I am currently developing a straightforward todo list application using JavaScript. The main functionality I am trying to implement is the ability to add new items from an input field to a list, as well as the option to remove items from the list. While ...

What could be the reason for my button not updating its text using a method?

I attempted to change the inner text of the Edit button to Save after it's clicked using a method, but it doesn't seem to be working. I could really use some help with this. b-button.editbtn.d-flex.flex-row.mb-3(@click="editBlood") ...

Implementing concurrent operations in React Native using Firebase, combining async/await with Promise.all

import fire from '../config/fire'; const db = fire.firestore(); class InitialDb extends Component { constructor(props) { super(props); this.state = { schools: '', students: '', }; } async compo ...

Is it possible to view the list of errors displayed by vscode when opening a JS file exclusively through the terminal?

Is there a default configuration file that vscode uses to display errors and warnings? I want to identify all issues in my JavaScript project. I don't have any jsconfig.json or tsconfig.json files, only using the //@ts-check directive in some files. ...

Including an <a> tag within a JavaScript variable to utilize in an HTML statement

I want to wrap an <a> element around a JavaScript variable containing a string. The desired output should be the 'copyright symbol' followed by the 'companyName' linked as an HTML link and then the current year's date. JavaS ...

Covering the entire screen, the Div element takes up the entirety of

Just like with other pages, the main div always takes up the entire screen visible to the user. As they scroll down, another div becomes visible: example1 , example2 Regardless of the screen size, the main div will always fill the space visible to the use ...

Guide to creating several AJAX requests using a for loop

I'm currently experimenting with the Star Wars API (SWAPI) and attempting to display the names of all the planets. However, the planet information is spread across multiple pages. How can I go about making several AJAX requests in order to retrieve an ...

Unfortunately, the datepicker feature does not seem to work properly on elements that have been dynamically added through the

My code progress so far is as follows: $('body').on('change', '.dropdown', function() { $.ajax({ success: function(res) { if(res.success == true) { return elements that have the class ...

Enhancing Element Generation and Data Association through jQuery

Currently, I am seeking a more streamlined approach to generate DOM alterations and update the object within .data(). At the moment, data is being supplied in an array of objects. I construct strings piecemeal, appending them to the table body, and affixi ...

What's the best way to trigger an event within a tag in a Vue.js component?

app.js Vue.component("popup",{ template : /*html*/` <div class="popup is-active" > <div class="popup-background"></div> <div class="popup-card"> <header class=" ...

This JavaScript operates in solitude, unable to collaborate with other JavaScripts

I received this code from an outsourced programmer: <script type="text/javascript"> $(function(){ $('#notif-icons > li > a, #top-menu > li > a').click(function() { var clicked = $(this).next('.popup-notif&a ...

Navigation bar transforms color once a specific scroll position is reached

My website features a sleek navbar fixed to the top of the window. As users scroll past a specific div, the background color of the navbar changes seamlessly. This functionality has been working flawlessly for me thus far. However, upon adding anchor link ...

The ng-bootstrap datepicker does not allow setting a default date prior to selection

I have implemented the ng-bootstrap date picker in my project and I am facing an issue with setting a default date for the input field before selecting a date from the datepicker itself. <input type="text" id="datepicker{{i}}" class="form-control" form ...

Why does the code require the use of window when the Javascript error object is not functioning properly?

I'm struggling to grasp the distinction between var maxResult = window.max(maxValInt1, maxValInt2); which functions properly, and var maxResult = max(maxValInt1, maxValInt2); which gives an error "object is not a function". Why do I have to inclu ...

The Angular ui-calendar introduces an innovative approach to event addition, providing users with

I need help with adding events to the angular ui calendar. Currently, I am using $scope.events.push() method to add events, but they get reset when changing the month. If anyone has experience with angular ui-calendar and event addition, please provide ...

Performance of obtaining image data

Is anyone else experiencing a significant lag when trying to retrieve the state of a single pixel on the canvas? Take a look at my JS code below: var state = ctx.getImageData(x,y,1,1).data; state = 'rgba(' + state[0] + ',' + state[1] ...