Calculate the values for top, left, width, and height in a Three.js projection

I'm currently facing an issue: I am trying to position a DIV on top of a WebGL animation. The scenario involves rotating a `mesh` using a `PlaneGeometry` to fill a rectangular area, and then placing the DIV at the top of that space. To achieve this, I need the X,Y coordinates and dimensions of the rendered plane.

My attempt with the `THREE.Projection` class did not yield the desired results, even after projecting the `[0]` vertex using `.projectVector`. The output was:

x: -0.1994540991160383
y: 0.17936202821347358
z: 0.9970982652556688

However, this information did not provide significant assistance.

Answer №1

To convert a 3D point called position to screen coordinates, with respect to the renderer's canvas, follow these steps:

var projector = new THREE.Projector();
var pos = projector.projectVector( position, camera );

var xcoord = Math.round( (pos.x + 1) * canvas.width / 2 );
var ycoord = Math.round( (-pos.y + 1) * canvas.height / 2 );

In this scenario, keep in mind that canvas refers to renderer.domElement.

If a point is located at the upper left corner of your visible world, it will project to coordinates (0, 0).

Based on three.js version r.53.

Answer №2

I have discovered the solution to this problem. It turns out that the top left point is actually the 0 index of the plane's vertices, but it's important to consider the transformations that have already been applied as well.

function calculateLayer()
{
    // The function multiplyVector3 takes into account the object's coordinates after transformations.
    var topLeft = tubeCard.matrixWorld.multiplyVector3( tubeCard.geometry.vertices[0].clone() );
    // Index 24 represents the bottom right point, given that the plane has 4x4 faces
    var bottomRight = tubeCard.matrixWorld.multiplyVector3( tubeCard.geometry.vertices[24].clone() );
    return {
            topLeft: convert3Dto2D( topLeft ),
            bottomRight: convert3Dto2D( bottomRight )
        }
}

function convert3Dto2D( positionVector )
{
    var projector = new THREE.Projector();
    var pos = projector.projectVector( positionVector, camera );

    var xcoord = Math.round( (  pos.x + 1 ) * window.innerWidth  / 2 );
    var ycoord = Math.round( ( -pos.y + 1 ) * window.innerHeight / 2 );

    return { x: xcoord, y: ycoord };
}

Once the correct coordinates with transformations are obtained, the 3d to 2d conversion by WestLangley can be utilized for further processing.

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

Different ways to call an ES6 class that is bundled in the <script> tag

Currently, I am utilizing Webpack to transpile my ES6 classes. Within the bundle, there is a Service class that can be imported by other bundled scripts. class Service { constructor() { // } someMethod(data) { // } } expo ...

Utilizing JavaScript as the front-end client for a web application connected to the backend of

I am facing an interesting scenario with a coworker who has suggested using JavaScript in a Web client application (specifically EPiServer CMS) to manage all the documents in the backend (SharePoint Online). However, I am unable to figure out how to acce ...

WordPress now features the ability to toggle both parent menu items when clicked, providing a more streamlined user experience

I am currently facing an issue with a menu structure, where parent menu items have submenus that need to toggle on click. However, I am encountering a problem where, upon placing the code inside a forEach loop, both submenus toggle instead of only togglin ...

Ways to mix up a term while maintaining the original first and final characters intact (Javascript)

I've been given a task to shuffle a word that has more than 3 letters while keeping the first and last letters unchanged. The revised word should not be identical to the original, ensuring some sort of rearrangement is apparent. For example, when sh ...

Alert message in jQuery validation for the chosen option value

I am attempting to validate a combo box with the code provided below. Currently, I receive multiple alert messages even if one condition is true. My goal is to only display one alert message when a condition is met and highlight the other values in red. Th ...

Guide to customizing Highcharts for extracting targeted JSON information

I've been dedicating a significant amount of time trying to unravel this puzzle. Typically, I prefer researching solutions rather than posing questions, but this challenge has me completely perplexed. My goal is to generate a Highchart using data from ...

Creating a basic tetrahedron shape using THREE.geometry is a straightforward process

Referencing the example provided in the THREEjs.org/docs: var geometry = new THREE.Geometry(); geometry.vertices.push( new THREE.Vector3( -10, 10, 0 ), new THREE.Vector3( -10, -10, 0 ), new THREE.Vector3( 10, -10, 0 ) ); geometry.faces.pus ...

Attempting to extract the class name of a tr tag but receiving a result of 'undefined'

I'm struggling to retrieve the class name from a specific <tr> tag. <table cellpadding=5 cellspacing=5> <tr id='cat_abc123' class='class_a'> <td>foo</td> <td><input type=& ...

I am facing an issue where the module pattern functions perfectly on JSBin, but fails to work properly

As a backend developer, I typically only write JavaScript when absolutely necessary, and not always in the best way. However, I have decided to turn over a new leaf and start writing more organized code that follows best practices as much as possible. To ...

Step-by-step guide for building and populating a JavaScript Dictionary

Does anyone know how to create a Dictionary with a key and a list of values pair in Python? I have been able to create dictionaries with a single value for each key, but now I need to store multiple items as values for each key. Here is what I have tried: ...

The HTML modal window is experiencing loading issues

I am attempting to implement a modal box that appears on click in an HTML document. The HTML code looks like this: <a href="#openModal">Open Modal</a> <div id="openModal" class="modalDialog"> </div> <a href="#openModal">O ...

Executing a JavaScript function within MainPage.xaml.cs codebehind file in a Windows application

I am currently working on a project developing a Windows 8.1 app using HTML5 and Javascript (Silverlight). I have encountered an issue with implementing the functionality for the hardware back button. Within the MainPage.xaml.cs Codebehind file, I need to ...

I am looking to dynamically add and remove an active link on my sidebar using JavaScript

Looking to create a dynamic website with interactive features like adding and removing active links upon clicking, and smooth transitioning between sections using JavaScript. Feel free to skip over the SVG code. HTML source code <div class="s ...

Storing the timestamp of when a page is accessed in the database

I am currently working on a PHP website where users can register and access exclusive Powerpoint presentations. The owner has requested that I track the amount of time users spend viewing each presentation, but I am unsure of how to display and record th ...

Looking to create circular text using HTML, CSS, or JavaScript?

https://i.sstatic.net/pnu0R.png Is there a way to generate curved text in HTML5, CSS3, or JavaScript similar to the image linked above? I've experimented with transform: rotate(45deg); but that just rotates the text without curving it. Additionally, ...

canvasJS: unable to load the chart

This is my first time using canvajs, but unfortunately, it's not working as expected. Can someone please review my code? data.php <?php header('Content-Type: application/json'); include './traitement.php'; $data =array(); ...

"Executing the command 'npm run dev' is successful, however, the command 'next dev' does not yield the expected result

Trying out Next for the first time using npx create-next-app, but running into issues with the scripts. While npm run dev works without any problems, executing next dev gives me an error saying zsh: command not found: next. Any idea why this is happening? ...

Submission error occurs if file upload is absent

When attempting to submit a form with a file, I encounter issues if the selected file for upload is changed (e.g. renamed) before submitting the form. The form fails to submit. Below is an example of my code: <form action="test.htm" method="post" encty ...

Are you interested in monitoring the website's past activity?

Similar Question: How to maintain browser history when utilizing Ajax? I've been trying to find a solution for this issue, but so far I haven't had any luck. Here's the thing: I created a template for my homepage that might not be perfe ...

Show an alternative option in the dropdown menu

Currently working with the Select component from Material UI, and here's what I'm trying to achieve:https://codesandbox.io/s/divine-water-zh16n?file=/src/App.js Situation: With an account object like {id:1, name:'name'}, I want to sel ...