Creating unique geometric designs with three.js

Attempting to construct a polygon in three.js and here is the code used for it.

function DeployZone(coordinatesList) {
// Forming the polygon Shape
{


    var material = new THREE.MeshLambertMaterial({ color: 0x00ffcc });

    var faces = [0, 1, 2, 3, 4];

    var geometry = new THREE.Geometry();
    for (var i = 0; i < coordinatesList.length; i++) {
        geometry.vertices.push(new THREE.Vector3(
            coordinatesList[i].x,
            coordinatesList[i].z,
            coordinatesList[i].y
        ));
    }


    for (var i = 0; i<faces.length; i++) {
        for (var j = 1; j < faces.length - 1; j++) {
            geometry.faces.push(new THREE.Face3(faces[0], faces[j], faces[j + 1]));
        }
    }

    geometry.computeFaceNormals();
    var zone = new THREE.Mesh(geometry, material);
    scene.add(zone);

}
}

The following are the coordinates passed:

var coordinatesList = new List<Coordinates>() {
      new Coordinates(X:0,Y:0,Z:0),
       new Coordinates(X:0,Y:10,Z:0),
       new Coordinates(X:5,Y:10,Z:0),
       new Coordinates(X:2,Y:8,Z:0),
       new Coordinates(X:5,Y:5,Z:0)
    };

A polygon is created but it's not exactly as desired. The vertex at (x:2,y:8,z:0) seems to misplaced. The issue lies with defining the triangular faces properly. Seeking assistance to make the faces and vertices dynamic so that the generated geometry is correct.

Appreciate any help provided.

P.S. Attempted working with shape but no success there. Also included this reference in the code.

Answer №1

Using the method THREE.Shape() is suitable for your situation:

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 grid = new THREE.GridHelper(30, 30, 0xffffff, 0x404040);
grid.rotation.x = Math.PI * 0.5;
scene.add(grid);

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


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

// Generate 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);


// Define lines
var matLines = new THREE.LineBasicMaterial({color: "magenta"});
var lines = new THREE.LineLoop(geom, 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>

Version used: Three.js r109

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

Error in browser caused by JQuery JavaScript, not Dreamweaver

I need help creating a webpage that can extract and display recent earthquake data based on user input location on Google Maps. I have been using Dreamweaver to test my code, and everything functions perfectly when I use the live webpage feature within th ...

Troubleshooting issues with filtering two MongoDB arrays in ES6 and finding a solution

I have a scenario where I am requesting two arrays of objectIDs from MongoDB, and then attempting to identify the differences between the two arrays. In addition, I am passing these arrays through express middleware using res.locals. Below is the code sn ...

Guideline on extracting private keys from Windows Certificate Manager

I am currently working in a Windows environment setting. Within my organization, we act as our own certificate authority for internally-used https applications. I have obtained a certificate from our system for a private web server I created. While using ...

The Ultimate Guide for Formatting JSON Data from Firebase

I'm facing an issue with parsing JSON data returned by Firebase. Here is the JSON snippet: { "-JxJZRHk8_azx0aG0WDk": { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cda6a68daaa0aca4a1e3aea2a0">[email&# ...

Is employing absolute paths in our confidential Node dependencies a good idea?

I have recently organized our codebase's React components into a separate dependency to make them reusable across different projects. To improve readability, all components now utilize Webpack aliases: import TestComponent from 'components/TestCo ...

What are the steps to take in order to successfully deploy an Express server on GitHub Pages?

I heard that it's possible to host an Express server on GitHub Pages, but I'm not sure how to do it. Is the process similar to deploying a regular repository on GitHub Pages? ...

The GET request is returning a null array instead of the expected array contents

I am new to this, but I am trying to understand why my GET request is returning an empty array even though I am sure that the Mongo database collection is not empty. Each word form in the WordForm collection has a "lexicalform" key that refers to a Lexicon ...

Strategies for handling axios responses within a useEffect hook in Reactjs

Currently, I am working with Reactjs and implementing nextjs. I am facing an issue where I am using Axios for fetching data from an API, but I am struggling to display it on the page. To debug this, I have tried using console.log inside the useEffect fun ...

Angular $watch not working as expected

I have a specific directive code: .directive('myDirective', function(){ 'use strict'; return { restrict: 'A' , link: function(scope, element, attrs) { var count = 0; function d ...

The post request is successful in Postman and cURL, however, it faces issues when executed in Angular

A remote server and a local client are set up to communicate through a simple post request. The client sends the request with one header Content-Type: application/json and includes the body '{"text": "hello"}'. Below is the s ...

Using JavaScript's Regex to match sentences, while ensuring any full stops within quotes are ignored

Here is the regular expression: (?:(?:Jr|Master|Mr|Ms|Mrs|Dr|Capt|Col|Sgt|Sr|Prof|Rep|Mt|Mount|St|Etc|Eg)\.\s+|["'“(\[]?)(?:\b(?:(?!(?:\S{1,})[.?!]+["']?\s+["']?[A-Z]).)*)(?:(?:(?:Jr|Master|Mr|M ...

When invoking a native prototype method, consider extending or inheriting object prototypes for added functionality

Recently, I came across a discussion on Inheritance and the prototype chain where it mentioned: Avoiding bad practice: Extension of native prototypes One common mis-feature is extending Object.prototype or other built-in prototypes. This practice, known ...

Is there a way to determine the size of an array following the use of innerHTML.split?

There is a string "Testing - My - Example" I need to separate it at the " - " delimiter. This code will help me achieve that: array = innerHTML.split(" - "); What is the best way to determine the size of the resulting array? ...

What is the best way to send information to a component using Props in Vue2?

Recently, I created a .Vue file to showcase information about a cafe on the Cafe Details Page. However, to streamline template updates, I decided to extract certain parts of this details page and turn it into its own component. This led me to create a new ...

What is the process for extracting content from CSS comments or annotations in a stylesheet?

Here's an interesting concept: allowing users to define a set of CSS rules with annotations. For example: /* @name Page style */ body { font: 16px/1.5 Arial; /* @editable */ background-color: #fff; /* @editable */ } /* @name Section header */ ...

Unable to update a property with a new value in Vue.js when using the keyup.enter event on an input element bound to that property

I am facing an issue with inputs that have the @keyup.enter event assigned to a method that is supposed to reset the value of variables bound to these inputs to null. Here is an example of my code: methods:{ clear: function () { this.somethin ...

Error: The module you are trying to import from the package is not found. Please check the package path and make sure that

I encountered an issue when trying to compile a code in Reactjs. As a beginner in Reactjs, I'm struggling with this. Module not found: Error: Package path ./cjs/react.development is not exported from package /Users/mansi/letsgrowmore/to-do-list/my-rea ...

Utilizing nested routes in Node.js with express.js framework!

index.js const AuthRouter = require("./Routes/Auth/signup") app.use("/account", AuthRouter) signup.js router.post("/", async (req, res) => { res.send("Signup") }) It's functioning correctly... H ...

Troubleshooting AngularJS form submission with missing data

Is there a way to modify AngularJS to save form data into a database using PHP as the backend? Below is the HTML form code: <form ng-submit="newContactSubmit()"> <label>FirstName<input type="text" name="contact_firstname" required n ...

Apply a new class to all Radio buttons that were previously selected, as well as the currently

Struggling with a simple code here, trying to figure out how to add color (class) to the selected radio button and the previous ones. For example, if button No3 is selected, buttons 1, 2, and 3 should get a new color. Below is the basic code snippet: < ...