Creating a Geometric Shape using Three.js

I'm currently utilizing Three.js to procedurally create a regular N-sided polygon based on a user-input number of sides. The ultimate objective is to use this as the initial phase in displaying a polyhedral prism.

To determine the vertices of the N-gon, I am following the method outlined here.

Subsequently, I am employing the approach discussed here to form faces on the N-gon.

My initial endeavor to construct the required Geometry object yielded unsatisfactory results, as it does not seem to render anything once incorporated into a Mesh:

function createGeometry (n, circumradius) {

    var geometry = new THREE.Geometry(),
        vertices = [],
        faces = [],
        x;

    // Generate the vertices of the n-gon.
    for (x = 1; x <= n; x++) {
        geometry.vertices.push(new THREE.Vector3(
            circumradius * Math.sin((Math.PI / n) + (x * ((2 * Math.PI)/ n))),
            circumradius * Math.cos((Math.PI / n) + (x * ((2 * Math.PI)/ n))),
            0
        ));
    }

    // Generate the faces of the n-gon.
    for (x = 0; x < n-2; x++) {
        geometry.faces.push(new THREE.Face3(0, x + 1, x + 2));
    }

    geometry.computeBoundingSphere();

    return geometry;
}

After struggling with that implementation for an extended period, I came across the ShapeGeometry class. This utilizes the same vertex algorithm as the previous example, but this time renders correctly when added to a Mesh:

function createShapeGeometry (n, circumradius) {

    var shape = new THREE.Shape(),
        vertices = [],
        x;

    // Determine the vertices of the n-gon.                 
    for (x = 1; x <= sides; x++) {
        vertices.push([
            circumradius * Math.sin((Math.PI / n) + (x * ((2 * Math.PI)/ n))),
            circumradius * Math.cos((Math.PI / n) + (x * ((2 * Math.PI)/ n)))
        ]);
    }

    // Begin at the final vertex.                
    shape.moveTo.apply(shape, vertices[sides - 1]);

    // Connect each vertex to the subsequent one sequentially.
    for (x = 0; x < n; x++) {
        shape.lineTo.apply(shape, vertices[x]);
    }

    // It's shape and bake... and I helped!         
    return new THREE.ShapeGeometry(shape);
}

What issues present in the Geometry example are resolved by the ShapeGeometry example?

I don't believe it pertains to camera or positioning since substituting the intricate vertex computations with straightforward whole numbers yields a polygon without difficulty, provided the values are logical.

I'm inquiring because, as stated earlier, my intention is to eventually employ this process to render a polyhedron. While ShapeGeometry objects can be extruded to add depth, even with the array of options offered by Three.js, this may fall short of meeting my requirements as the desired polyhedra become more irregular.

Any insights?

Answer №1

If you're looking to create prisms in your Three.js project, consider using THREE.CylinderGeometry. For a prism with n sides, you can define it like this:

// radiusAtTop, radiusAtBottom, height, segmentsAroundRadius, segmentsAlongHeight
var nPrism = new THREE.CylinderGeometry( 30, 30, 80, n, 4 );

Not only can CylinderGeometry be used for prisms, but also for building pyramids and frustums. For more examples of predefined shapes, take a look at:

If you have an interest in exploring general polyhedra, check out:

This resource includes models of various polyhedral shapes like the Platonic Solids, Archimedean Solids, Prisms, Antiprisms, and Johnson Solids. However, note that these polyhedra are rendered with a "thick" appearance using spheres for vertices and cylinders for edges.

I hope this information proves useful to your project!

Answer №2

Your function is functioning correctly.

Check out this code snippet http://jsfiddle.net/Elephanter/mUah5/

You can see a modified threejs fiddle with your createGeometry function

It seems like the issue lies elsewhere, and not with the createGeometry function as you suspected

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

javascript popup window with redirection functionality

Hello everyone, I need assistance with the code snippet below: echo ("<SCRIPT LANGUAGE='JavaScript'> window.alert('Successfully Updated') </SCRIPT>"); I am trying to redirect the page to my edit.php after c ...

Experience some issues with the NextJS beta app router where the GET request fails when using fetch, but surprisingly works

Having an issue with a GET request while using NextJS with the APP dir... The function to getProjects from /project route.ts is not triggering properly. console.log("in GET /projects") is never triggered, resulting in an unexpected end of JSON ...

Guide on showcasing html and css in a preview using a Data URL

Currently, I have implemented two tab interfaces: one for entering HTML text and another for inputting CSS content. Following this, I have included a Preview section to visualize the combined output of both HTML and CSS elements. However, I am encountering ...

Exploring the process of generating, monitoring, and initiating personalized events in ReactJS

To establish a global custom event for listening and triggering purposes, here is how it can be achieved using jQuery: $(document).on('myCustomEvent', function(){ console.log("myCustomEvent triggered"); }) $(document).trigger('myCustom ...

Is there a JavaScript/jQuery timer for re-invoking a method?

Currently, I am developing a basic animation with jQuery that utilizes the hover method. The issue arises when a user hovers over the same image twice, causing the method to be re-invoked. Any recommendations on how to implement a "timer" to prevent the ...

Retrieve specific items from a handlebars array by using the loop index

Utilizing handlebars.js, I am iterating through the categories and then accessing an element in the series array using the current array index. This is achieved with the following helper function. var json={ "categories": [{ "id": 3, ...

Eliminating the top and bottom sections of a website when embedding it in an in-app frame

Recently, I developed a Wordpress website located at My client has requested to embed this terms and conditions page into an app to streamline updates. However, the challenge is how to remove the website header and footer when displaying it in the app. I ...

AngularJS Error: $element.find(...) does not support iteration

I'm attempting to utilize a datatable in my AngularJS application. Below is the HTML code I've implemented: <div ng-app="datatable"> <div ng-controller="voucherlistcontroller"> ...

Tips for showcasing live data in Material-UI's table component

My challenge lies in displaying tabular data fetched from an API in a Material-UI Table. Specifically, I aim to exhibit the fields id and name stored within groups. How can I achieve this result? Beneath is my current code snippet which runs without error ...

Is there a way to make a NodeJS Transform stream produce multiple records for each input chunk?

Currently, I am working on a Transform stream that has the capability to receive an incoming stream of XML data and then emit a subset of that in the form of JavaScript objects. <item> <name>some name</name> <files> <fil ...

Designing a file upload progress bar with the help of jquery and ajax

I am looking to implement a progress bar for uploading files utilizing jquery and ajax. Here is the jquery code I have written: function updateProgress(evt) { // evt is an ProgressEvent. if (evt.lengthComputable) { var percentLoaded = ...

The slick slider fails to function properly within a bootstrap dropdown menu

My bootstrap navigation includes a dropdown in which I want to integrate a slick slider. However, all the items get displayed together when the dropdown is opened. The slider functions properly outside of the dropdown and also works when the dropdown has ...

Retrieve the image by its unique identifier while viewing a preview of the image before it is uploaded

Below is the script I am using to preview an image before it is uploaded. The HTML structure looks like this: <div> <img id="image" src="#"> </div> <input type="file" accept="image/gif, image/jpeg, image/png" onchange="readURL(th ...

Fill in datatable with information from a JSON array if there are missing values in certain columns

My goal is to populate a datatable in JavaScript. Currently, I am able to do so, but some of the last rows have blank columns which are populated first. I attempted to fill those blank columns, and then the data populates in order. Here is an example of my ...

What is the best way to utilize JavaScript prototype methods in Angular 2+ templates?

Is it possible to utilize JavaScript global object constructors, such as Array, within the angular 5 view without having to explicitly declare them in the component? In my particular case, I require access to Array.from() directly within the view. Curren ...

Troubleshooting problems with AngularJS placeholders on Internet Explorer 9

On my partial page, I've included a placeholder like this: <input name="name" type="text" placeholder="Enter name" ng-class="{'error':form.name.$invalid}" ng-model="Name" required /> I have also set up client side validation for the ...

Using Three.js to create a vector representation on a plane

As a newcomer to three.js (and stackoverflow), I am struggling to find the answer to a seemingly simple problem. I am experimenting with Helpers and Plane objects in an attempt to create a Plane and draw a vector on it. Everything works fine when the plane ...

What is the best way to link my JSON object to specific properties of my data object in vue.js?

I am currently using Vue.js for my frontend development and I have a JSON object that I need to map to set certain properties in my data(). I have confirmed that the server connection is working and that the JSON object is received properly. In my comput ...

Retrieve the ActiveTabIndex value from an Ajax TabContainer using Javascript

Is there a way to retrieve the ActiveTabIndex from TabContainer when a tab is selected by the user? I've attempted the following approach without success. <script type="text/javascript"> function GetActiveTabIndex() { var tc = docum ...

Winning awards through the evaluation of possibilities

I became intrigued by the idea of using a chance algorithm to simulate spinning a wheel, so I decided to create some code. I set up an object that listed each prize along with its probability: const chances = { "Apple" : 22.45, & ...