Troubleshooting Three JS Projection Challenges

I have been attempting to find the centroid of a polygon in 3D space and then convert its vertices to 2D screen coordinates. Unfortunately, the code I currently have is not producing the desired results. I would greatly appreciate any assistance with this problem.

//calculate the centroid
var centroid = new THREE.Vector3();
for (var i = 0; i < positions.length; i++) {
    centroid.add(positions[i]);
}
centroid.multiplyScalar(1 / positions.length);
//focus camera on centroid
var camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
camera.lookAt(centroid);
//calculate the screen coordinates
for (var i = 0; i < positions.length; i++) {
    screenPositions.push(convertToScreenXY(positions[i], camera, width, height));
}

function convertToScreenXY(position, camera, width, height) {
    var pos = position.clone();
    pos.project(camera);
    var halfWidth = width / 2,
        halfHeight = height / 2;
    return {
        x: (pos.x + 1) * halfWidth + halfWidth,
        y: (-pos.y + 1) * halfHeight + halfHeight
    };

}

It seems that the camera transformations are not being applied correctly to the projection.

Answer №1

After adjusting the camera's rotation, be sure to update the camera's world matrix as the project() method relies on it.

camera.position.set( newX, newY, newZ );
camera.lookAt( newCenter );

camera.updateMatrixWorld(); // make sure to include this line

Normally, the renderer automatically triggers camera.updateMatrixWorld() during renderer.render(), but in this situation, it needs to be manually invoked.

Version of three.js being used is r.71

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

Relocating to the middle of the webpage (Automatically resize for mobile compatibility if feasible)

Apologies for my poor English. Are there any suggestions on how to center this without using margins or other methods? Perhaps there are alternative solutions. https://i.sstatic.net/dXfwL.png Also, is it feasible for the image and video to automatically a ...

Can you provide me with some insight on the process of iterating through an object utilizing the

I've developed an app that randomly plays a sound from a selected array when a button is pressed. Now, I want to add the functionality to display and play all sounds in the array upon request. I've explored various methods such as for loops and ...

Is there a way to reach (req , res) within a middleware function?

My custom Authorize Middleware allows only authorized users to access the dashboard: router.get('/dashboard', authorize(), dashboard); This function checks for user roles before granting access. Here is how it works: const jwt = require('e ...

Mouse over effect to highlight the crosshair on a table

My code currently enables a crosshair function, but I am looking for a way to limit the highlight effect only within the cursor (hover) area. Instead of highlighting in a "cross" shape, I would like it to show a backward "L" shape. This means that the hig ...

What is the method for replacing browser bundle sources using Rollup?

Is it possible to use rollup to swap out a specific source with another source in an NPM package when creating a browser bundle? The source in question is loaded dynamically using import('./relativeFile.js') (I need this to be replaced). I attem ...

Can one look through a div to the one beneath it by moving the cursor?

Hey there! I have a unique question for you. I've been trying to achieve a specific effect where two divs are stacked on top of each other, and the content of the lower div is only revealed in a certain area around the cursor. Is it possible to make o ...

Discovering the exact location of an object within a rotating parent object

Inside my THREE scene, there is an Object that rotates. The child object is positioned at (92, 92, 92) within the rotating Object, orbiting the center position (0, 0, 0) in a spherical path with my mouse movement. How can I determine the global position of ...

Marionette stores a collection for various item views

I am currently working on a project involving a composite view called QueueItems, with each item in the collection having its own itemView for modification. The challenge lies in allowing each element to select from multiple tag collections like States, Co ...

Using jQuery on the client-side to interact with a MongoDB database

Currently, I'm in the process of developing a basic example application to gain experience with using MongoDB. My goal is to create a single web page that can interact with a local MongoDB server by adding and removing content dynamically through jQue ...

Prevent incorrect data input by users - Enhancing JavaScript IP address validation

I have been trying to create a masked input field for entering IP addresses, but every solution I come across seems to have some flaws. The best solution I found so far is , but it still allows values higher than 255 to be entered. It works fine initially ...

Determine the number of elements chosen within a complex JSON structure

I need to figure out how to count the length of a jsonArray, but I'm stuck. Here's an example to start with: https://jsfiddle.net/vuqcopm7/13/ In summary, if you click on an item in the list, such as "asd1", it will create an input text every t ...

The processing indicator fails to function properly when trying to refresh a jQuery datatable

I am currently customizing the loading indicator for the datatable using a spinner called startLoadGlobal(SPINNER_DATA_TABLE_FINANCEIRO_CARREGAR_REGISTROS) in jQuery. It works correctly when I initially load the datatable, however, when I reload it, the sp ...

Transmitting a client-side JavaScript function to the server for processing the database response and generating a downloadable CSV file

I need to create CSV reports for a series of queries in my project. In the backend, I have a general POST request handler in nodejs/express that accepts a JSON object structured like this: { "converter": <converter function>, "fields": < ...

Activation of states in response to item clicks

Recently, I started using the US-Map plugin created by newsignature (). I have put together a chart that highlights various state laws for comparison on a per-state basis. Currently, the setup allows me to compare 3 states at a time. Users can easily clos ...

What is the best way to implement a required input field in Vue.js?

I need some assistance with my chat functionality. I want to prevent users from sending empty messages, so I want to make the input field required. Can you please help me with this? I have already tried adding "required='required'" to the input ...

I'm experiencing difficulties inserting data into my RECHARTS chart

I have several sets of data arrays from an API that I receive, and I need to use the [1] index of each array on the line and the [0] index on the axis of my chart. DATA SET 31) [Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2), Array(2 ...

Encountering an error when attempting to include React TypeScript onChange with a Material UI switch component

I'm working on implementing a show/hide functionality using a switch. I want the component to be displayed when the switch is turned on and hidden when it's turned off. Here's the code I've written: const VirtualEventSection = ({ con ...

Here is a method to display a specific string in the mat-datepicker input, while only sending the date in the backend

enter image description hereIn this code snippet, there is a date input field along with a Permanent button. The scenario is that when the Permanent button is clicked, it should display "Permanent" in the input UI (nativeElements value), but the value bein ...

Having trouble with the npm package installation for react-circular-progressbar

I encountered an error when trying to install react-circular-progressbar in my React projects. Why is this happening? npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/em ...

Having trouble with errors when adding onClick prop conditionally in React and TypeScript

I need to dynamically add an onClick function to my TypeScript React component conditionally: <div onClick={(!disabled && onClick) ?? undefined}>{children}</div> However, I encounter the following error message: Type 'false | (() ...