Mesh height determines the color scheme in Three.js

After loading an STL file using the STLLoader() in Three.js and converting it into a mesh, I am interested in coloring each cube of the mesh based on its height. The goal is to achieve a visual effect similar to the one shown in this image screenshot-color-by-height. Can this be done with Three.js? If so, what would be the most effective approach to accomplish this? You can view the actual model here:

Answer №1

Exploring the possibilities of incorporating vertex colors into your project:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 1000);
camera.position.set(2, 5, 10);
var renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);

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

var light = new THREE.DirectionalLight(0xffffff, 0.5);
light.position.setScalar(10);
scene.add(light);
scene.add(new THREE.AmbientLight(0xffffff, 0.5));

var planeGeom = new THREE.PlaneBufferGeometry(10, 10, 10, 10);
planeGeom.rotateX(-Math.PI * 0.5);
var yMin = 0;
var yMax = 2;
var colors = [];
for (let i = 0; i < planeGeom.attributes.position.count; i++) {
  let yVal = THREE.Math.randInt(yMin, yMax);
  let yNorm = (yVal - yMin) / (yMax - yMin);
  planeGeom.attributes.position.setY(i, yVal);
  colors.push(yNorm, yNorm, 1);
}
planeGeom.addAttribute('color', new THREE.BufferAttribute(new Float32Array(colors), 3));
planeGeom.computeVertexNormals();

var mesh = new THREE.Mesh(planeGeom, new THREE.MeshStandardMaterial({
  vertexColors: THREE.VertexColors
}));
scene.add(mesh)

render();

function render() {
  requestAnimationFrame(render);
  renderer.render(scene, camera);
}
body {
  overflow: hidden;
  margin: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/92/three.min.js"></script>
<script src="https://threejs.org/examples/js/controls/OrbitControls.js"></script>

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

Placing a list item at the beginning of an unordered list in EJS with MongoDB and Node.js using Express

What I've done: I already have knowledge on how to add an LI to UL, but it always goes to the bottom. What I'm trying to achieve: Add an LI to the top so that when my div.todos-wrapper (which has y-oveflow: hidden) hides overflow, the todos you a ...

"Exploring the process of unsubscribing or disposing of an interval observable based on a certain condition in Angular2 or

I am embarking on the journey into Rx and reactive programming, facing a situation that requires me to continuously monitor a hardware's status by sending a POST request to its REST API every 500ms. The goal is to stop the interval observable once the ...

Unexpected twist observed when custom curve is applied to Threejs TubeGeometry

After creating a custom curve applied to TubeGeometry, I noticed an interesting behavior. The curve's vertices on the X axis change based on mouse movement, while the Z axis follows a simple sin curve affected by time. The code snippet below demonstra ...

Interfacing with Ajax to dispatch information to a PHP script

Hello, I'm currently working on implementing Ajax in my web application. However, I've encountered a small issue. I'm attempting to check if a username has already been registered by controlling a form. The problem arises when my JavaScript ...

Enabling Multi-Row Form Submission in jQuery: Ensure Submit Button is Disabled Until Every Row Has a Checked

I am dealing with a multi-row form that contains single choice radio buttons in each row. My goal is to have the final <button> tag disabled until a radio button has been checked in each row. Although I have found a solution from a previous question ...

Is there a method to update the res object following a couchbase DB call without encountering the error "Error: Can't set headers after they are sent"?

let express = require('express'); let searchRoute = express.Router(); searchRoute.get('/', function(req, res, next) { console.log('1'); databaseCall(function(error, result) { if (error) { res.sta ...

Issue with Navigation bar: Bootstrap menu fails to open upon clicking

My Bootstrap menu is experiencing an issue where it fails to open when I click on it. This means that I can't see any items in the menu. However, when I press the "Down key" on my keyboard, it opens immediately. This issue seems to occur specifically ...

The improper utilization or replacement of Jest mock in an Angular standalone component's unit test is causing issues

Presented here is a streamlined Ionic/Angular component with unnecessary code removed. import { IonicModule, ModalController } from '@ionic/angular'; @Component({ selector: 'my-component', templateUrl: 'my-component.html' ...

The webpage becomes unresponsive due to an Ajax request

Creating a generic way to call ajax requests on my webpage has been challenging. I've developed an extension method for calling post requests asynchronously. $.tiqPost = function(action,data,callback) { alert('Posting...'); $.fancyb ...

Tutorial on how to update a specific value in an array of objects using setState on click event

I need to toggle the active class on click, setting it to a local state and changing all other objects in the state to inactive. const [jobType, setJobType] = useState([ { "class": "active", "type& ...

Establishing Node.js environment variables when invoking `npm run` command

package.json { "scripts": { "start": "NODE_ENV=development node ./index.js" } } If we wanted to pass and override NODE_ENV when running npm run start, is it possible? npm run start NODE_ENV=production ...

Facing an issue with Heroku deployment where a React/Express app is encountering a 'Failed to load resource' error in the console while requesting the chunk.js files

Upon deploying my React application on Heroku, I encountered errors in the console. Refused to apply style from 'https://radiant-tor-66940.herokuapp.com/index.css' because its MIME type ('text/html') is not a supported stylesheet MIME ...

Leveraging the spread operator for setting state in a series of consecutive updates

Within my component, I am retrieving values from local storage and attempting to load them into the state when the component mounts. However, only the last property that I add seems to be included in the state. I have confirmed that all values are present ...

What criteria should I use to determine if a post has been favorited by a user using Mongoose?

Creating a function for users to like posts has been my recent project. Each post is stored as an object in my MongoDB collection with a specific schema. { title: String, text: String } On the other hand, users have their own unique schema as well. ...

Tips for incorporating a favicon in a React application

Having trouble adding a favicon to my React application. I followed the instructions in this post, but it's not working for me. I placed the favicon.ico file inside the public folder where index.html resides. This is how my directory structure looks ...

Why isn't `$watch` being triggered following a jQuery `onchange` event

Having trouble getting $scope.watch to trigger... $scope.amountselected = 5; $scope.qtyselected = 1; $scope.$watch(['qtyselected'], function () { console.log($scope.availbleprecheckout); }); jQuery(document ...

Dealing with Unicode Issues in JSON Encoding and MySQL

Here is some JavaScript code that I have: The code works fine (the makewindows function has been changed to show it as a PHP variable), but there seems to be an issue with Unicode characters in the HTML. Only characters before the first Unicode character ...

Steps for leveraging pdfMake with live data

Recently delving into Angular, I've been exploring the capabilities of pdfMake. While I successfully incorporated static data, I'm facing challenges when attempting to utilize dynamic data. Any guidance on how to achieve this would be greatly app ...

Generate a random number to select a song file in Javascript: (Math.floor(Math.random() * songs) + 1) + '.mp3'

My current JavaScript code selects a random song from the assets/music folder and plays it: audio.src = path + 'assets/music/'+(Math.floor(Math.random() * songs) + 1)+'.mp3' However, I've noticed that sometimes the same trac ...

Allow undici fetch requests to use self-signed certificates

What is the correct way to execute fetch('https://localhost:8888') when dealing with a locally hosted HTTP server that uses a self-signed certificate (using fetch which is derived from undici)? ...