Create Mesh from Three.js Points

I'm attempting to create an interactive shape in Three.js by using points generated from mouse clicks.

Below is the code that I currently have:

mouse.x = ( ( event.clientX - renderer.domElement.offsetLeft ) / player.width ) * 2 - 1;
mouse.y = - ( ( event.clientY - renderer.domElement.offsetTop ) / player.height ) * 2 + 1

raycaster.setFromCamera( mouse, camera );

var objects = [];
objects.push(selectedHotspot);

var intersects = raycaster.intersectObjects( objects, true  );

if ( intersects.length > 0 ) {
    var point = new THREE.Mesh( new THREE.SphereGeometry(1, 1, 1), new THREE.MeshBasicMaterial( { color: 0x00ffff } ) );
    point.position.copy(intersects[0].point);
    scene.add(point);
    points.push(intersects[0].point);
}

var geometry = new THREE.Geometry();

points.forEach( function( point ){
    geometry.vertices.push( point );
});
geometry.vertices.push( points[0] );

geometry.faces.push( new THREE.Face3(0, 1, 2));

// material
var material = new THREE.MeshBasicMaterial( { color: 0xffffff } );

// line
var line = new THREE.Mesh( geometry, material );
scene.add( line );
hotspots.push( line );

The points are successfully added and lines are drawn between them. However, I am struggling with filling in the center so the shape can be detected by the mouse!

Answer №1

To generate a mesh from a set of points, you can utilize THREE.ConvexGeometry.

var mesh = new THREE.ConvexGeometry( vertices_array );

For a practical example, check out

This output represents the convex hull based on your input points and should be suitable for your requirements.

Make sure to explicitly import the three.js file

examples/jsm/geometries/ConvexGeometry.js
into your project's source code.

Version: three.js r.147

Answer №2

When it comes to transforming a point cloud into a mesh, there are several methods you can explore based on your specific requirements. Here is a general summary of some potential approaches:

One possibility is to utilize a bounding box. By calculating the bounding box of the point cloud and performing raycasting against this BBox, you may find that this simple method suffices for your needs.

However, if the bounding box includes large areas devoid of points, you might need a more precise mesh around the point data. One approach involves projecting all points onto a plane perpendicular to the ray and then creating a 2D convex hull using the Gift wrapping algorithm. Various libraries likely implement this algorithm, making it a convenient option for generating a polygon to use in the raycasting process.

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

Where should the logic for the Redux app be implemented for optimal performance?

My react-redux app features an action-creator that filters a list of objects based on a specified title: export const filterItems = (title) => dispatch => { axios.get(`/api/items/?title=${title}`) .then(res => { dispatch({ ...

The action is undefined and cannot be read for the property type

Using the React+Redux framework, I encountered an error: https://i.sstatic.net/0yqjl.png During debugging, the server data successfully reached the state, but the action was empty: https://i.sstatic.net/41VgJ.png Highlighted below is a snippet of my co ...

How can custom CSS and JS be loaded in Sencha Touch based on the user's device - PC, tablet, or smartphone?

Is there a way to configure a webpage so that when the user is accessing it from a PC (using Safari/Chrome/Firefox), they see the "normal" version of the page, but if they are using an iPad to view the same URL, they get Sencha Touch (css, js) files in t ...

The act of coming back with just one array

I'm having trouble grasping the concept of returning a single array from a function that calls another function multiple times. The issue I'm facing is that each time the scrapingfunction runs, the console.log in the code provided outputs an arra ...

Run a Node command when the button is clicked

I am developing a web application where I need to run a node command upon clicking a button. Instead of manually executing the node command in the command line, I want it to be triggered by a click on the front end. For example: $( ".button_class" ).on( ...

'this' in Arrow functions does not have a reference to the calling context

Something seems off about the context in this code. I've left comments to describe my issue below: const cat = { //arrow function meow: () => { console.log(this); }, makeMeow(){ // Why does 'this' refer ...

The Google map shifts beyond the perceived limits of the world

Is anyone else encountering an issue with Google Maps where you can now pan beyond the poles? It used to stop at the poles before, correct? The website I'm currently working on runs a location-based query on our server every time a user pans or zooms ...

Solving the puzzle of closing a challenging JavaScript popup with Selenium in JavaScript

Dealing with popups in Selenium can sometimes be tricky, especially when encountering unusual behavior. I recently encountered a situation where I found it difficult to close a popup window after clicking a button. Upon executing the code below: WebEleme ...

IE11 is encountering an error with an "Expected identifier" message in the vendor.js file related to Webpack's variable

I encountered an issue with an Expected identifier ERROR code: SCRIPT1010 that is pointing to vendor.js in the WEBPACK VAR INJECTION section. The debugger is highlighting the line with: const { keccak256, keccak256s } = __webpack_require__(/*! ./hash */ ...

Is it necessary to include the jQuery-Do alert command before using console.log() in JavaScript or jQuery code?

const firstResponse = ""; $.get("firstCall.html", function (response) { processResponse(response); }); function processResponse(content) { firstResponse = content; } const secondResponse = ""; $.get("seco ...

Error: Unhandled promise rejection: [object Boolean]

I am encountering an issue while trying to secure a route in my Angular application. Despite what I believe to be the correct implementation, I am facing an error message when the negative scenario is triggered: ERROR Error: Uncaught (in promise): [object ...

The jQuery function triggers in the console upon first click but does not display in the browser. However, it shows up twice in the browser upon

I'm quite puzzled by this issue. In my javascript file, the jQuery functions (including the one located at the end of the page) seem to skip the first click event and respond twice on the second click. I am also utilizing Bootstrap in my project. App ...

Caution: Prop type validation failed due to an invalid value being passed to ForwardRef(Slider)

Currently, I'm in the process of building a Material UI range Slider with two values. It functions correctly if initialized like this: const [value, setValue] = React.useState([5,20]); const [value, setValue] = React.useState([val]); const handl ...

Using a JavaScript variable within an Angular component: a step-by-step guide

I am currently working with some javascript code for mapbox in my .ts file within an angular component. My goal is to access a variable called polygonCoordinates[] from the javascript code and use it in my typescript code. Unfortunately, I'm facing di ...

Building multi-dimensional array checkboxes in AngularJS - a step-by-step guide

I am working with a multi-dimensional array and I need to display all the data using checkboxes. The array below contains dietary requirements, and I want to create checkboxes for each entry where the value is true. How can I use ng-repeat to iterate over ...

Guide to dynamically updating the content of a textGeometry in threeJS

I attempted the following code snippet: var fontLoader = new THREE.FontLoader(); fontLoader.load("/assets/fonts/helvetiker_bold.typeface.json",function(font){ var text2D = new THREE.TextGeometry(newText.textContent, { ...

Why is it not possible to isolate the function for xmlHttp.onreadystatechange?

The JavaScript file named test.js is functioning properly when included in my HTML. function sendData() { var formData = new FormData( document.querySelector("form") ); var xmlHttp = new XMLHttpRequest(); xmlHttp.open("post", "test.php",true); ...

awaitMessages feature does not capture slash commands

In my development process, I have a file named botReady.js that is designed to run as soon as the bot becomes ready. In this file, there is a specific section dedicated to handling a bump bot in a designated channel obtained using the client.channels.fetch ...

Error in Sequelize database: Column name does not exist in the database

The issue at hand involves a findAll product selector with a column labeled "PermissionId" that does not actually exist. I am puzzled as to why Sequelize is generating this non-existent column. The errors encountered are as follows: Unhandled rejectio ...

Vue.js: The Power of Manipulating Strings

Why is the filter method not working with this.userId, but it is working with the hard-coded value "admin"? How can I resolve this issue? computed: { UidMessages: function() { return this.Messages.filter(function(m) { return m ...