A guide on obtaining the pixel dimensions of a ThreeJS mesh object: determining its visible width and height

I am currently grappling with the task of determining the visible view width and height of a ThreeJS mesh object in pixel units.

In the image provided below, you can observe objects suspended in 3D space. Upon clicking the mouse, I need to be able to discern the exact view width and height they occupy in pixels. https://i.sstatic.net/esBr7.jpg

Due to my novice status in ThreeJS, finding a solution is proving to be time-consuming. Any help or guidance would be greatly appreciated.

The function outlined below showcases the various approaches I have been experimenting with.

getObjectSizeInViewSpace(object){
      const size = new THREE.Vector3()
      const box = new THREE.Box3().setFromObject(object).getSize(size)
      size.project(this.camera)

      let halfWidth = window.innerWidth / 2;
      let halfHeight = window.innerHeight / 2;

      size.x = (size.x*halfWidth)
      size.y = (size.y*halfHeight)
      
      return new THREE.Vector2(size.x,size.y)
  }

Answer №1

If you're in search of the Vector3.project() method, look no further. This function transforms 3D world-space coordinates into normalized device coordinates using the camera's viewport, ranging from [-1, 1]. For instance, a value of x: -1 corresponds to the left side of the screen and x: 1 signifies the right side. To determine the pixel dimensions of your plane in the browser, you must calculate the vectors for all four corners:

// Obtaining 3D positions for the top left corner (assuming no rotation)
vec3 topLeft = new Vector3(
    plane.position.x - planeWidth / 2,
    plane.position.y - planeHeight / 2,
    plane.positon.z
);

// Mapping x, y, z values to the [-1, 1] range
topLeft.project(camera);

// Converting from [-1, 1] to [0, windowWidth]
const topLeftX = (1 + topLeft.x) / 2 * window.innerWidth;
const topLeftY = (1 - topLeft.y) / 2 * window.innerHeight;

Take note that the topLeftY value is inverted since in 3D space, negative y moves to positive y in pixel coordinates. Repeat this process for each corner and then compute the difference between the right and left points to obtain the width, repeating the same for the height.

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

Explaining the implementation of JQuery's onload event and its impact on reducing dependencies

Contained within a table is some data https://i.stack.imgur.com/gQyJQ.png Upon clicking the edit button, I am able to modify the information in that specific row. The Menu Category and Menu are populated through Dependent dropdowns. https://i.stack.imgur ...

Place a div element directly into a specific cell within the table

How can I place the following div <div class="inner"> <p>The first paragraph</p> <p>The second paragraph</p> </div> into a specific cell within a table? I am open to using either plain JavaScript or jQuery, althou ...

Tips for refreshing the tawk.to widget when the language changes with the help of i18next

Utilizing i18n-jquery for language switching and integrating the tawk.to chat widget, I've successfully loaded different languages on page reload. However, due to i18n not refreshing the page (which I don't want to do), I need to figure out how t ...

When running the command `npm install <node_module> --save`, the dependencies are not being updated as

<=== If you're facing the same issue, try reinstalling your computer to fix it ===> I recently had to reformat my computer and set everything up again. After reinstalling Node and NPM, I encountered some problems that are really irritating me. ...

The DOM element fails to load when utilizing the ng-view attribute

Recently, I have started working with AngularJS for my first web application and everything is running smoothly. However, I am now looking to integrate some charts using jQuery. The issue arises when trying to load a chart upon clicking on a menu item in ...

Refrain from using inline JavaScript code within your

Here is the basic structure of my code: <a href="javascript:void(0);" onClick="viewServices(1)">Services</a> <a href="javascript:void(0);" onClick="viewServices(43)">Services</a> <a href="javascript:void(0);" onClick="viewServic ...

disable the form submission function in dropzone when buttons are clicked

Dropzone is being utilized on my page in the following manner alongside other input types such as text and select dropdowns: <form name="somename" method="post" action="/gotoURL" form="role"> // Other form elements here <div id="dropare ...

The functionality to show the login status is currently malfunctioning

I have a login status indicator section on my homepage which is connected to an ajax-php database. The login button performs two actions when clicked. <input value="Login" type="button" onclick='logInUser(/*function to handle login request*/);upda ...

Exploring techniques to maintain search functionality on altered display columns in DataTables.js

How can I ensure that the search functionality works properly on the modified render column in DataTables.js? In the code snippet provided below, my attempts to search data within the render columns are not yielding any results. $('#release-table& ...

Duplicate a Google Sheet and save it to a specific folder in Google Drive

I currently have two spreadsheets in my possession. The first spreadsheet consists of raw data that includes unique employee numbers and the names of the employees. The second spreadsheet is the one I aim to duplicate to a designated Google Drive folder. M ...

How can one overcome CORS policies to retrieve the title of a webpage using JavaScript?

As I work on a plugin for Obsidian that expands shortened urls like bit.ly or t.co to their full-length versions in Markdown, I encounter a problem. I need to fetch the page title in order to properly create a Markdown link [title](web link). Unfortunatel ...

What is a more efficient way to differentiate a group of interfaces using an object map instead of using a switch statement?

As someone still getting the hang of advanced typescript concepts, I appreciate your patience. In my various projects, I utilize objects to organize react components based on a shared prop (e.g _type). My goal is to automatically determine the correct com ...

Matching request parameters with a JSON object using node.js and express framework

After uncommenting the lines, the code runs smoothly. However, whenever I enable the 'else' statement, I consistently receive a 'not found' message even when there is a match between req.params.code and data.airports[i].code. var exp ...

Dealing with GraphQL mutation errors without relying on the Apollo onError() function

When managing access to an API call server-side, I am throwing a 403 Forbidden error. While trying to catch the GraphQL error for a mutation, I experimented with various methods. (Method #1 successfully catches errors for useQuery()) const [m, { error }] ...

What is the best way to retrieve information in Next.js when there are changes made to the data, whether it be new

Could you share a solution for fetching data in Next.js when data is added, deleted, or edited? I tried using useEffect with state to trigger the function but it only works when data is added. It doesn't work for edit or delete operations. I have mult ...

Achieving enlightenment with Satori in NextJS: Transforming SVG to PNG in a NodeJS Environment

I am currently exploring the capabilities of satori and integrating it into my next.js api routes. (I'm unable to utilize the vercel/og package). While I have successfully set everything up, I'm facing a challenge in converting the svg image gen ...

Angular's use of ES6 generator functions allows for easier management of

Recently, I have integrated generators into my Angular project. Here is how I have implemented it so far: function loadPosts(skip) { return $rootScope.spawn(function *() { try { let promise = yield User.findAll(); $time ...

The Kendo Grid is not displaying any data when trying to bind the data source using an ajax callback to the controller

My query is quite similar in nature to this: Binding Kendo Data Source with Async $.ajax calling from C# MVC Controller Action Below is the javascript code used for generating the Kendo grid: $(document).ready(function () { $("#grid").kendo ...

What is the best way to retrieve nested reference data all at once from a Firestore document?

I have two distinct collections stored within my Firestore database. The first collection is users, and it can be visualized as shown here: https://i.stack.imgur.com/AKlyM.png The second collection is posts, represented by the following structure: http ...

How can I organize data from A to Z in alphabetical order in React Native when the user chooses the A to Z option from the dropdown menu?

I am working on a screen that can display up to 1000 data retrieved from the API. Here is the image: https://i.sstatic.net/ErbDD.png Now, I have implemented a drop-down box where users can select alphabetically from A to Z. After selecting an alphabetic ...