Converting Three JS from 3D to 2D dimensions

I am looking to convert the world space coordinates of a sphere into screen space coordinates in order to determine the screen space boundaries, which I then plan to use for overlaying a div element.

It would be great if this function could also provide the height and width of the object, along with its x & y positioning:

toScreenPosition : function (obj, camera) {

    var vector = new THREE.Vector3();

    var widthHalf = 0.5*world.renderer.context.canvas.width;
    var heightHalf = 0.5*world.renderer.context.canvas.height;

    obj.updateMatrixWorld();

    vector.setFromMatrixPosition(obj.matrixWorld);
    vector.project(camera);

    vector.x = ( vector.x * widthHalf ) + widthHalf;
    vector.y = - ( vector.y * heightHalf ) + heightHalf;


    return { 
        x: vector.x,
        y: vector.y
    };

},

Answer №1

To project the border of a main object onto the screen, begin by creating multiple THREE.Object3D elements and positioning them around the main object.

Apply the necessary methods used on the main object to these additional objects in order to determine the pixel positions of the main object's border on the screen.

For instance, if you need to find the screen coordinates of a sphere with a radius of 5:

var obj1 = new THREE.Object3D();
var obj2 = new THREE.Object3D();
var obj3 = new THREE.Object3D();
var obj4 = new THREE.Object3D();

obj1.position.set(sphere.x, sphere.y + 5, sphere.z);
obj2.position.set(sphere.x, sphere.y - 5, sphere.z);

Then, instead of using the regular function, update their matrix world individually like so:

obj1.updateMatrixWorld();
obj2.updateMatrixWorld();

This will provide you with the x,y coordinates of these objects (located around the main object) on the screen, allowing you to calculate the height difference as needed.

Answer №2

To solve this problem, I propose creating a function that accepts a 3D point as input and outputs the corresponding 2D screenpoint. An example of such a function can be found here. When dealing with a sphere, the process becomes simpler: first, find the center of the sphere in 3D space and calculate its corresponding 2D point. This point will serve as the center of the overlay div. Next, choose any 3D point on the surface of the sphere, compute its 2D point, and determine the necessary radius for the overlay div based on these calculations. With this information, it is straightforward to derive the dimensions of a rectangular area that encompasses the sphere.

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

Conflict between multiple jQuery files

Currently, I am in the process of creating a test website for an upcoming project. However, I have encountered some issues with jQuery. This is a static HTML5 website that includes a social widget. The problem arises when I remove a particular jQuery lin ...

Is there a way to utilize the reset() function within an input form?

Is there a way to automatically reset the textbox when submitting a value? Below is my code: <!DOCTYPE html> <html> <body> <ul id="myList"> </ul> <input type="text" id="myText" value="&q ...

The React.useCallback hook in Cube.js is missing a dependency, specifically 'pivotConfig'. This could potentially cause unexpected behavior in the application

After multiple attempts at creating a straightforward dashboard using Cube.js with Windows 10 and MySQL version 8, I am feeling frustrated. Initially, I experimented with a JavaScript backend, struggled through the installation process for days, then attem ...

I need to obtain the URL pathname on a server component in Next.js version 13 - how is this achieved

I'm facing an issue with retrieving the pathname of a server component located in the app directory. Despite attempting to obtain it through window.location, I haven't been successful. Is there an alternative method I can use to achieve this? ...

Navigating a double entry validation in a Java script prompt while utilizing Selenium

Can someone please assist me with the following scenario: I need to complete a double entry check prompt/alert that contains two text boxes. The task is to fill in these two text boxes and then click on the OK button. Potential solutions attempted: I tr ...

Manipulate the url bar using ajax and window.location

When making an AJAX request using .load, everything works perfectly. However, there is an issue with the URL bar. I am trying to change the URL displayed in the bar. For instance, when the ajax loads the about/contact page, I want the URL bar to show about ...

Toggle the visibility of a table row depending on the selected value of a Radio button

I have a jQuery script that I am working on, which toggles the visibility of table rows based on the selection of radio buttons. The current code functions properly when a radio button is clicked, but I would like to enhance it to automatically show or hid ...

Is there a method to save the req object from a callback route to a file using NodeJS?

I have a requirement to save my req/res object to a file for future reference when redirecting to a specific page. Here is what I attempted: app.get("/route", function(req, res) { res.render("route"); fs.writeFile('./data.json', JSON.stringify ...

Save information for each session with a set expiration time

Currently, I am working on a mobile application using Angular (specifically Ionic 5) and I am in need of a solution to maintain session data for my users throughout their workflow. Initially, I thought about utilizing the sessionStorage feature for this p ...

Issue: React error message indicates that the .map() function is not recognized. The API response is in the form of an object, making

As a newcomer to REACT.JS, I am currently facing the challenge of extracting data from an API for my project. Utilizing "Axios" for sending the get request, I have encountered a situation where the response comes back as an array in one API and as an objec ...

Maintain cookie persistence beyond browser shutdown

Using this code snippet in Node-Express JS, I am creating a cookie with a JWT token included. Here is the code: var token = jwt.sign(parsed.data, "token_secret", {expiresIn: "43200m"}); res.setHeader('Set-Cookie', 'token='+token+&apos ...

What exactly does the symbol "++" signify in the context of jQuery and JavaScript

Throughout my observations, I have noticed people employing i++, especially within a for-loop. However, the specific purpose of ++ when used with a variable remains unclear to me. My attempts to locate documentation explaining its function have been unsuc ...

Is JSON required to transmit an object using socket.io?

I have an object on the frontend that I want to broadcast to all connected clients. Can I send it as is, in its original form? Or do I always have to convert it into a JSON string before sending? Here is my object: var myBox = { x: 400, ...

Setting the select option in AngularJS with predefined options can be easily achieved with

I am encountering an issue with a select element that has predefined options. Even though the select element is using ng-model, when the model is set to one of the option values, it fails to be selected. Below is the snippet of HTML code: <select clas ...

Navigate to a specific section of a webpage with automatic scrolling

I'm developing a Chrome App and incorporating the web view tag, which functions similarly to an iframe. Is there a way to load a webpage inside the web view halfway down the page? I have attempted the following: application.js: $(document).ready(f ...

Utilize Postman to send a JSON body in a POST request to trigger a stored procedure on Microsoft SQL Server

I need to send a JSON request using the Postman app, utilizing the POST method to retrieve data. My boss, who is overseeing my training, assigned me this task. I've scoured the web for a week but haven't found a solution yet. Initially, I sugges ...

What are some solutions for resolving the npm error code elifecycle issue?

After following the documentation, I successfully installed React JS but encountered an error when trying to run the app. The error code displayed was elifecycle npm err errno 1. Can someone please assist me in resolving this issue? Additionally, it's ...

Ways to conceal an element in Angular based on the truth of one of two conditions

Is there a way to hide an element in Angular if a specific condition is true? I attempted using *ngIf="productID == category.Lane || productID == category.Val", but it did not work as expected. <label>ProductID</label> <ng-select ...

The necessity of utilizing a dummy object for storing events in JavaScript is evident in certain situations

I am confused as to why in some instances a dummy object is needed in JavaScript to store events, like in the following code: Metal.Gold = function() { var temp = $("<div>"); //dummy object this.Submit = function(url1, method, data){ ...

Encountering an error while trying to import GraphQL resolvers and schema

Upon attempting to start the server with the following setup, an error is encountered: Error: "createUser" defined in resolvers, but has an invalid value "function (userInput) {... The resolver's value must be of type object. index.ts const schema ...