Randomly order the vertices and incident polygons for three.js fill color on a face

Recently, I delved into learning three.js and am eager to figure out how to fill in the face color after creating a polygon based on randomly given vertices. Can anyone guide me on how to achieve this?

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(60, window.innerWidth / window.innerHeight, 1, 100);
camera.position.set(0, 5, 10);
camera.lookAt(0, 5, 0);
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 grid = new THREE.GridHelper(30, 30, 0xffffff, 0x404040);
grid.rotation.x = Math.PI * 0.5;
scene.add(grid);

var coordinatesList = [
  new THREE.Vector3(2, 0, 5),
  new THREE.Vector3(0, 10, 3),
  new THREE.Vector3(5, 10, 4),
  new THREE.Vector3(2, 8, 2),
  new THREE.Vector3(5, 5, 1)
];


// Shape
var geomShape = new THREE.ShapeBufferGeometry(new THREE.Shape(coordinatesList));
var matShape = new THREE.MeshBasicMaterial({color: "blue", side: THREE.DoubleSide});
var shape = new THREE.Mesh(geomShape, matShape);
scene.add(shape);

// Points
var geom = new THREE.BufferGeometry().setFromPoints(coordinatesList);
var matPoints = new THREE.PointsMaterial({size: 0.55, color: "pink"});
var points = new THREE.Points(geom, matPoints);
scene.add(points);


// Lines
var matLines = new THREE.LineBasicMaterial({color: "magenta"});
var lines = new THREE.LineLoop(geom, matLines);
scene.add(lines);


renderer.setAnimationLoop(() => {
  renderer.render(scene, camera);
});

For reference, you can check out the jsfiddle here: https://jsfiddle.net/d9quczhe/

Answer №1

If you encounter a similar situation, one way to handle it is by allocating the Z-coordinate from an array of coordinatesList to the corresponding point in your geometry:

var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 25;
camera.lookAt(new THREE.Vector3(0, 5, 0));
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 gridHelper = new THREE.GridHelper(30, 10);
scene.add(gridHelper);

var coordinatesList = [
  new THREE.Vector3(2, 0, 5),
  new THREE.Vector3(0, 10, 3),
  new THREE.Vector3(5, 10, 4),
  new THREE.Vector3(2, 8, 2),
  new THREE.Vector3(5, 5, 1)
];

// Generating shape based on coordinatesList ///////////////////////////////////////////
var geomShape = new THREE.ShapeBufferGeometry(new THREE.Shape(coordinatesList));

// Assigning Z-coordinates from initial vectors ///////////////////////////////////////
let positions = geomShape.attributes.position;
for(let j = 0; j < positions.count; j++){
    positions.setZ(j, coordinatesList[j].z)
};
geomShape.computeVertexNormals();
//////////////////////////////////////////////////////////////////////////////////////

console.log(geomShape)

var matShape = new THREE.MeshBasicMaterial({color: "blue", side: THREE.DoubleSide});
var shape = new THREE.Mesh(geomShape, matShape);
scene.add(shape);

// Creating points
var geomPoints = new THREE.BufferGeometry().setFromPoints(coordinatesList);
var matPoints = new THREE.PointsMaterial({size: 0.55, color: "pink"});
var points = new THREE.Points(geomPoints, matPoints);
scene.add(points);

// Drawing lines
var matLines = new THREE.LineBasicMaterial({color: "magenta"});
var lines = new THREE.LineLoop(geomPoints, matLines);
scene.add(lines);

renderer.setAnimationLoop(() => {
  renderer.render(scene, camera);
});
body{
  overflow: hidden;
  margin: 0;
}
<script src="https://threejs.org/build/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

Adding information to an HTML table using JQuery

Is there a way to incorporate JSON data into an HTML table? The JSON data follows this format: https://i.stack.imgur.com/lzdZg.png This is the desired HTML table structure: <table class="table table-bordered table-hover "> ...

Error encountered while installing Material UI in Next.js with TypeScript and pure JavaScript configurations

I'm brand new to React and Next.js, so please forgive me for asking what may seem like a silly question. I'm attempting to install Material UI in a fresh Next.js application that I created using "npx create-next-app@latest". I've been refere ...

JavaScript: Choosing between explicit imports and the * sign

Why do this in one way: import * as copy from 'copy-to-clipboard'; instead of the other way: import { someMethod } from 'copy-to-clipboard'; Does it impact performance or bundle size? Personally, I find the second option cleaner. ...

Can state be controlled by both the parent and children within the same element?

I am facing a situation where I have a component that requires updating the value from its parent, but also needs to handle user input changes without having to pass them back to the parent. See this scenario in action with this example: https://codesandbo ...

Executing all middleware within an express route

Currently, I am in the process of constructing an API using express and have implemented multiple middleware functions in my routes. One of the endpoints I am working on is displayed below: Router.route('/:id/documents') .get([isAuthenticated, ...

Understanding the readability of JavaScript arrays.ORDeciphering

Recently, I've been working with a JSON OBJECT that looks something like this { "kay1": "value1", "key2": "value2", "key3":{ "key31": "value31", "key32": "value32", "key33": "value33" } } However, I am interested in converting it ...

Can select2 and a jQuery Virtual Keyboard work together seamlessly?

Is there a method to implement a jQuery virtual keyboard for inputting into a Select2 select box? The issue is that the dropdown in the Select2 component closes automatically when clicked away from, preventing the use of a web-based virtual keyboard. If ...

What is the best tool for syntax highlighting with Vue.js?

Looking for guidance on syntax highlighting with Vue.js. I've included the code snippet below, but for some reason the message "This is a test" isn't appearing as expected. Can someone please point out what mistake I may be making? <html> ...

The syntax for specifying the post body content in frisby.js is important

My current setup involves smooth UI and server data exchange, but I am interested in exploring new development possibilities with Frisby.js. The UI utilizes a JavaScript form manager powered by jQuery. To send the request body, I first serialize a JavaScri ...

The call stack in mongodb has surpassed its maximum size limit

I am currently executing a method. Method execution var message = "Hello" function1("78945612387", message, null, "Portalsms") Node JS Code function function1(mobileno,body,logExtraInfo,messageType){ request(uri, function (error, resp ...

One efficient way to handle multiple concurrent tasks in NodeJs is by using the forEach method to iterate

Having trouble getting the promises to return any values, as they are coming back empty. Despite following suggestions on Stack Overflow, I am still unable to resolve this issue. Frustration levels are high and I'm feeling lost; Can anyone help me pi ...

Evaluate a program to identify prime numbers

I am currently working on a JavaScript program that utilizes recursion to determine whether an input is a prime number or not. Within my code, I've defined the isPrime function. The base cases are set to return false when x==1 and true for x==2, cons ...

Place the div directly beside the input field on the right side

I am attempting to align a div directly beside the text being entered in a text input field. It seems logical to me that this could be achieved by measuring the length of the input value and positioning the div accordingly. However, the issue I am facing i ...

error in three.js occurs when attempting to load .obj files

I've been encountering issues with OBJ files that I've downloaded from the internet. All of these files render like this: View Obj File Pic I'm using the standard OBJLoader for rendering. var loader = new THREE.OBJLoader(); loader.load( ...

What are effective strategies for safeguarding my AngularJS application code, particularly from unauthorized access through the browser's source code?

I am currently working on an AngularJS application. I have encountered a challenge where the end user is able to view the app code from the browser's source code. I am seeking advice on how to address this issue effectively. Is there any recommended ...

RegEx not triggering Mongoose hooks

When performing queries on my mongo collections, I am attempting to call specific hooks for them. DispatchRequest.findOneAndUpdate({user_name:"umesh"},{email:"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cdac8 ...

Encountering unexpected behavior with the .data() method

I'm encountering an issue with my code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv= ...

Node.js and Express - Dealing with Callbacks that Return Undefined Prematurely

I've hit a roadblock with this issue that's been haunting me for weeks. The first function in my code queries a MySQL database and returns a response, which is then processed by the second function. The problem lies in the fact that JavaScript ...

Avoid HTML code injection in an ExtJS4 grid by properly escaping the href attribute

I am facing an issue with escaping HTML in my Extjs grid. I have used the following configuration : return Ext.String.htmlEncode(value); In the renderer of my column, this method works perfectly for simple HTML tags like h1, b, i, etc. However, if I in ...

In order to have a Node.js program run synchronously following a for loop

I am struggling with ensuring that the last console statement is executed only after all iterations of the for loop are completed. Currently, this console statement executes immediately once control enters the else statement. Any ideas on how to resolve ...