Guide to creating 2D point shapes with three.js

Is there a way to render a 2D shape of points in three.js? I have been struggling to find a working geometry for this task. I simply want to create a polygon of points that lie on the same plane.

The 'Shape' object doesn't seem to be suitable as it only supports 2D coordinates and I need to work with 3D points...

Currently, I am using the code below to create a shape in the X,Y plane:

 var squareShape = new THREE.Shape();
 squareShape.moveTo( 0, 0 );
 squareShape.lineTo( 0, 50 );
 squareShape.lineTo( 20, 80 );
 squareShape.lineTo( 50, 50 );
 squareShape.lineTo( 0, 0 );

How can I adapt this to work in a 3D world? Is there a solution like this:

squareShape.moveTo( 0, 0, 0 );
squareShape.lineTo( 0, 50, 50 );

Any suggestions or guidance would be greatly appreciated.

Answer №1

To create a polygon using 3D coordinates, follow this code snippet:

// Define the geometry
var geometry = new THREE.Geometry();
geometry.vertices.push( new THREE.Vector3( 6, 4, -1 ) );
geometry.vertices.push( new THREE.Vector3( 7, -5, 0 ) );
geometry.vertices.push( new THREE.Vector3( -9, -3, 3 ) );
geometry.vertices.push( new THREE.Vector3( 6, 4, -1 ) ); // Complete the shape

// Specify the material
var material = new THREE.LineBasicMaterial( { color: 0x00ff00, linewidth: 2 } );

// Create the line
var line = new THREE.Line( geometry, material );
scene.add( line );

Using three.js version r.82

Answer №2

Starting from release 51, a new form of geometry known as THREE.ShapeGeometry has been introduced. This type of geometry represents two-dimensional shapes that lie on a single plane. An illustrative example showcasing its application can be accessed through this link:

To create a 2D shape using THREE.Shape, you can utilize the method shape.makeGeometry() to convert it into a THREE.ShapeGeometry. Below is a pseudo-code snippet demonstrating how to generate a circle:

var circle = new THREE.Shape();
var radius = 6;

for (var i = 0; i < 16; i++) {
  var pct = (i + 1) / 16;
  var theta = pct * Math.PI * 2.0;
  var x = radius * Math.cos(theta);
  var y = radius * Math.sin(theta);
  if (i == 0) {
    circle.moveTo(x, y);
  } else {
    circle.lineTo(x, y);
  }
}

var geometry = circle.makeGeometry();
var material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
var mesh = new THREE.Mesh(geometry, material);

The resulting mesh object possesses attributes such as position, rotation, and scale, allowing you to manipulate and position the object within a three-dimensional space.

Answer №3

To generate a geometry with the vertices of the shapes (after extraction) and apply triangulation to define the faces, follow these steps:

Here is an example of how the code should be structured:

const geometry = new THREE.Geometry();
const shapePoints = shape.extractPoints();
const faces = THREE.Shape.Utils.triangulateShape(shapePoints.shape, shapePoints.holes);
for (let i = 0; i < shapePoints.shape.length; i++) {
    geometry.vertices.push(new THREE.Vector3(shapePoints.shape[i].x, 0, shapePoints.shape[i].y));
}
for (let i = 0; i < faces.length ; i++) {
    const a = faces[i][2], b = faces[i][1], c = faces[i][0];
    const v1 = shapePoints.shape[a], v2 = shapePoints.shape[b], v3 = shapePoints.shape[c];

    geometry.faces.push(new THREE.Face3(a, b, c));    
    geometry.faceVertexUvs[0].push(
        [new THREE.UV(v1.x, v1.y), new THREE.UV(v2.x, v2.y), new THREE.UV(v3.x, v3.y)]);
}
geometry.computeCentroids();
geometry.computeFaceNormals();

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

Learn the process of utilizing Uglify.js to combine JavaScript files for individual views within Express.js

My website is currently built on express.js and I am looking to optimize my JavaScript files using uglify.js in the build process. An example of a typical view on my site appears as follows: extend layout block head script(src="/js/polyfills/html5s ...

Calculation of time intervals based on input values from text boxes, calculating quarters of an hour

I am facing a couple of challenges: -I am trying to calculate the time duration in hours between two military times input by the user in two textboxes. The result should be in quarter-hour intervals like 2.25 hours, 2.75 hours, etc. -The current calculat ...

Difficulty executing for loop due to multiple buttons, resulting in malfunctioning buttons in JavaScript code

Currently encountering an issue while trying to implement modal windows on my first website. Everything works fine without the for loop, but I wanted to have multiple buttons and windows, so I decided to use a for loop to handle each button. Strangely, the ...

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 ...

Difficulty in transferring a variable from my JavaScript file to my PHP file

Currently, I am utilizing the Instascan API to scan QR codes with the intention of sending the scanned content to my PHP file. However, regardless of whether I use POST or GET methods, the PHP file does not seem to recognize them and keeps expecting either ...

Interacting with icons using TouchableOpacity and onPress functionality

I am attempting to implement onPress functionality for icons using TouchableOpacity. However, when I click on the icon, nothing happens and there are no console logs displayed. I have also tried enclosing the icon within an additional View, but that appro ...

Encountering a Javascript Error when trying to begin

As a beginner in Javascript, I am venturing into designing a simple website that incorporates Javascript. Currently, my focus is on building a calculator. However, upon loading my website, nothing seems to initiate and there are no error messages displayed ...

Is it possible that JavaScript isn't functioning properly?

My current issue involves echoing JavaScript from a PHP file to an HTML page using AJAX. Strangely, the JavaScript does not run when dynamically echoed, even though it appears in the Inspect Element tool. On the other hand, purely textual content echoes su ...

Tips for creating a partial matching filter on an array using elements from a separate array

My goal is to filter an array by finding partial matches from another array. To illustrate, consider the following arrays: Array1 = categories: 292300, categories: 300, categories: 292500280 Array2 = 300, 498 After filtering, ...

Issues with sending an AJAX POST request to a PHP script

Hello, I am trying to send a variable from an AJAX JavaScript file to a PHP file. Here is what I have done so far: var request = createRequest(); var deletenode = node.id; window.alert("nodeid=" + deletenode); var vars = "deletenode ...

changing a variable in javascript

Is there a way to successfully update the "storage" variable set in uploadify? I have a function called set_path that is designed to modify the variable by combining it with other values whenever specific content is selected. $(document).ready(function () ...

underscore.js does not allow data to be manipulated outside of the _.each

Struggling to get my head around utilizing the underscore loop in jQuery's $.ajax function for retrieving a JSONp file... Within the success section, I have the following code snippet: success : function(response) { var dataResp = '' ...

Transfer data between an HTML page and a PHP page hosted on separate locations using jQuery

Below is the code snippet I am currently working on: function send_data() { var a=$("#username").val(); var b=$("#password").val(); $.post("http://localhost/login/login.php", {uname: a, pswd: b}, function(data) { $("#result").html(data); }); ...

Retrieve an image from the database and associate it with corresponding features or news in PHP

I have retrieved a value from the database, displayed it as an image, and made it a link. So, I want that when a user clicks on the different image, they get the result from the query related to the image. I hope everyone understands. <?php // Connect ...

Converting an array into a JavaScript Date object

I am currently working with an array of dates and looping through each element. The elements within the array are not date objects but rather strings, I believe. When I print each of the elements to the console, they appear as follows: 2015,09,19 2015,09, ...

Utilizing the NuxtJS framework to tap into video camera functionalities

I am completely new to Vue and NuxtJs. My goal is to create a webcam feature using NuxtJs, but I have encountered some challenges. <template> <div class="photobooth"> <div class="controls"> <button @click="takePhoto">Ta ...

The frisbyjs test is not passing due to the absence of proper HTTP headers being sent by the get()

My frisbyjs test is failing because the x-access-token and x-key HTTP headers are not being sent. Am I missing something? This seems like a simple mistake. Here is the outer test that contains the failing test within afterJSON(): frisby.create('Logi ...

Retrieving JSON data with jQuery's Ajax functionality

I'm currently developing a web application to handle the administrative tasks for a restaurant. The main functionalities include creating new orders, adding order items, and managing financial overviews. One of the key features is the ability to view ...

When using Vue.js, the class binding feature may not function properly if it is referencing another data property that has variants

I am currently developing a basic TODO application. Within my index.html file, I have a main div with the id #app. Inside this div, there is another div with the class .todobox where I intend to display different tasks stored in my main.js file. Each task ...

Utilizing external libraries with RiotJS for greater functionality

My jQuery flexslider is causing slide animation issues because the library is being loaded before the DOM. As a result, I can't trigger actions of the flexslider. Here's the HTML structure: <html> <body> <home-templat ...