Utilizing Three JS to add Gradient to external Models

When it comes to comparing the gradient colors applied to two spheres, the key lies in one statement:

sphereGeometry = sphereGeometry.toNonIndexed();

https://i.sstatic.net/pBBs9.jpg

https://i.sstatic.net/KRULV.jpg

I prefer the smoother look achieved by .toNonIndexed(), so I attempted to apply it to some of the imported “.glb” models from THREE.js GIT - but encountered issues.

For instance, when I tried it on the horse model available here: https://github.com/mrdoob/three.js/blob/master/examples/models/gltf/Horse.glb

https://i.sstatic.net/IUQ9Y.png

The colors were completely overridden and defaulted to red and black inexplicably.

However, if I remove the .toNonIndexed() line, the requested colors are displayed - although the triangular structure is prominent, which goes against the smooth look I aim for:

https://i.sstatic.net/f2Z4x.png

Below is the code snippet for loading the object:

function loadAny3DModel() {
    loader.load("./Horse.glb", function(theHorse) {
       console.log("===>'theHorse' has arrived!!!\n");

       var horseScene = theHorse.scene;
       horseMesh = horseScene.children[0]; 
                
       var horseGeometry = horseMesh.geometry; 
       let horseMat = horseMesh.material;
       var horseVertexPositionsArray = horseGeometry.attributes.position;

       // The problematic command:
       // horseGeometry = horseGeometry.toNonIndexed(); 
       // horseVertexPositionsArray = horseGeometry.attributes.position;

        let theColor = new THREE.Color();
        let colorsArray = [];
        for(let i = 0; i < horseVertexPositionsArray.count; i++) {
          let randC1 = "purple"; 
          let randC2 = "white";
          let chosenColor = i % 2 == 0 ? randC1 : randC2;
          theColor.set(chosenColor);
          colorsArray.push(theColor.r, theColor.g, theColor.b);
        }
        horseGeometry.setAttribute("color", new THREE.Float32BufferAttribute(colorsArray, 3));
        horseMat.vertexColors = true;

        render();
        scene.add(horseScene);

    }
}

How can I achieve a smoother gradient effect?

=====================================================================

UPDATE:

Here's my concept: extending a gradient across an entire model rather than each individual triangle forming it. (Compare this image to the one above.)

https://i.sstatic.net/2J4sZ.jpg

Answer №1

When you include the code in the line below...

horseGeometry = horseGeometry.toNonIndexed();

...it indicates that a new geometry is being created. However, if you do not reassign the geometry to Mesh.geometry, this code will not have any impact. To resolve this, simply add the following line after using toNonIndexed():

horseMesh.geometry = horseGeometry;

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

selection menu and advancement gauge

While working on my code, I have a task where I need to make the progress bar move a specific amount when a name is clicked based on the option's value. <!DOCTYPE html> <html> <head> <title>testinggg</title> &l ...

What occurs when a numerical value is added to an element within an array?

Illustration 1: Let numbers = [4,5,6] + 2; console.log(numbers) // "4,5,62" typeof numbers // String Illustration 2: let nums = 10 + ["w","o","r","l","d"]; console.log(nums) // "10w,o,r,l,d"; typeof nums // String When combining a number or string wi ...

Mastering the A-Frame Game Loop: Tips for Separating Logic and Rendering

Currently, I am experimenting with A-Frame and my Quest 2 headset in order to create a simple VR game. One particular challenge I am facing is understanding how to separate logic from rendering and establish a proper game loop. After discovering this tutor ...

Exploring textboxes with jQuery loops

Is there a way to clear all these textboxes by iterating through them using Jquery? <div class="col-md-4" id="RegexInsert"> <h4>New Regex Pattern</h4> <form role="form"> <div class="form-group"> &l ...

Total the values of several items within the array

Here is the data I currently have: const arrayA = [{name:'a', amount: 10, serviceId: '23a', test:'SUCCESS'}, {name:'a', amount: 9, test:'FAIL'}, {name:'b', amount: ...

Ways to create dynamic functionality with JavaScript

I need to iterate through the document.getElementById("b") checked in a loop. Is this achievable? How can I implement it? <img class="img-responsive pic" id="picture" src="images/step1.png"> <?php //get rows query ...

Why isn't the page redirecting if the query is unable to locate the user?

Why does the application freeze when it fails to find a user, instead of redirecting to the main page? How can this issue be resolved? User.findOne({_id: userid}, function(err, user) { if(err) { res.redire ...

Can Highchart dynamically adjust color choices based on the quantity of data points available?

I am trying to figure out how to import a specific color palette into my column graph. I want to use different color palettes based on the number of data points in my graph - for 3 or fewer points, I want to use the top row colors, for 4 points I want to u ...

Efficiently finding a group of substrings within a JavaScript string

I am currently working on a method to efficiently search for specific substrings within a given string. Here is my current implementation: const apple = "apple" const banana = "banana" const chickoo = "chickoo" const dates = & ...

Querying data in Laravel from a table with two foreign keys referencing the same table

I am facing an issue with mapping relations in Laravel Eloquent for two tables: teams and games. The teams table has id, group_id, and name fields, while the games table includes id, home_team_id, away_team_id, date, and score. The problem arises from the ...

Passing data to child Vue component and iterating through it

Working with the axios call to fetch data from an API has been my current challenge. I am aiming to integrate the Home and ListItem components seamlessly. <template> <div> <list-item v-for="idea in ideaList" :key="idea.id" ...

Tips for importing font files from the node_module directory (specifically otf files)

We cannot seem to retrieve the fonts file from the node module and are encountering this error message. Can't find 'assets/fonts/roman.woff2' in 'C:\Projects\GIT2\newbusinessapp\projects\newbusinessapp\src ...

The ckeditor vanishes upon refreshing the div element

I have created two pages named openclosediv.php and content.php. The openclosediv.php page contains a list of records and a button that can show/hide the div, bringing in the content from content.php. However, I am facing an issue where the CKEditor in the ...

Updating Mysql through REST API/JWT using PUT method is not possible

I have been attempting to send an update request using Jwt (Tokens) and Node.Js with a backend in mysql. While Postman confirms that the record has been successfully updated, I am unable to locate where the actual update occurred. No changes seem to be ref ...

Is it possible to eliminate the arrows from an input type while restricting the change to a specific component?

Is there a way to remove the arrows from my input field while still applying it only to the text fields within this component? <v-text-field class="inputPrice" type="number" v-model="$data._value" @change="send ...

Configuring Request Limits in a Meteor.js Application

I'm encountering an issue while trying to send a large amount of JSON data to a server-side route in my Meteor.js application. The error message I keep receiving is: Error: Request Entity Too Large at Object.exports.error (/mnt/data/2/node_module ...

Changing the length of a vector in THREE JS by its absolute value

I am working with two Vector3 points, A and B. My goal is to determine vector C, positioned along the trajectory path from point A to point B, while also extending its length by 100 units. Can someone guide me on how to calculate this vector? ...

Utilizing Next.js named imports without server-side rendering

I am looking to update this code snippet to use next.js dynamic imports without server-side rendering (SSR) import { widget } from "./charting_library/charting_library"; Here is what I have tried so far const widget = dynamic(() => import(&qu ...

Creating a POST method in AngularJS

Here is the code snippet I am working with: var req = { method: 'POST', url: '/customer', headers: { 'Content-Type': 'application/json' }, data: { test: 'testvalue' } }; $http(re ...

Utilizing PHP and jQuery Ajax in conjunction with infinite scroll functionality to enhance filtering capabilities

I have implemented infinite-ajax-scroll in my PHP Laravel project. This project displays a long list of divs and instead of using pagination, I opted to show all results on the same page by allowing users to scroll down. The filtering functionality works s ...