Mapping three-dimensional coordinates to a two-dimensional screen location

My goal is to develop an interactive GUI for my app using threejs. I came across this informative tutorial:

The tutorial provides the exact information I need, but it refers to an older release.

function getCoordinates(element, camera) {

    var p, v, percX, percY, left, top;
    var projector = new THREE.Projector();
    // This function will give us position relative to the world
    p = element.position.clone();
    console.log('projected position', p);
    // The projectVector translates the 3D position to 2D
    v = p.project(camera);
    console.log('projected vector', v);

    // Translating our vector so that percX=0 represents
    // the left edge, percX=1 is the right edge,
    // percY=0 is the top edge, and percY=1 is the bottom edge.
    percX = (v.x + 1) / 2;
    percY = (-v.y + 1) / 2;

    // Scaling these values to our viewport size
    left = percX * window.innerWidth;
    top = percY * window.innerHeight;

    console.log('2d coordinates left', left);
    console.log('2d coordinates top', top);

}

I had to update projector to vector.project and

matrixWorld.getPosition().clone()
to position.clone().

When passing position (0,0,0), I noticed that

v = {x: NaN, y: NaN, z: -Infinity}
, which was not expected.

The camera being passed is

camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 1, 10000)
.

Answer №1

function extractCoordinates( element, camera ) {

    var screenVector = new THREE.Vector3();
    element.localToWorld( screenVector );

    screenVector.project( camera );

    var posX = Math.round(( screenVector.x + 1 ) * renderer.domElement.offsetWidth / 2 );
    var posY = Math.round(( 1 - screenVector.y ) * renderer.domElement.offsetHeight / 2 );

    console.log( posX, posY );
}

http://jsfiddle.net/gH8Kv1yz/13/

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 is the session management functionality situated within an OAuth-enabled web application?

When creating an oauth service (such as for Facebook or Gmail) enabled web application using Angular or React, where should session management be located? Should user sessions be maintained on the hosted server or within the oauth service itself? This is ...

React Native: Enhance the background with a vibrant stripe of color

I am trying to incorporate a strip of grey in the middle of my white background, but I am encountering an issue where I am unable to input any text inside it. Below is the code snippet I am working with: container: { flex: 1, justifyContent: "cent ...

Passing a value to a component to delete a table row in ReactJS using Material UI

My task is to delete a specific table row after clicking. I have two components and have already written a function, handleDelete(), to remove a row from the table. The issue is that whenever I click, it always deletes the last row instead of the one I cli ...

Is there a method to enclose a Grafana row with a border?

I recently created a Grafana dashboard using JavaScript and I realized that adding a border around each row would enhance readability. Here is how the current view looks like: https://i.stack.imgur.com/itKYR.png However, it can be difficult to differenti ...

Incorporate a new tab based on specific conditions in Excel 2016/365 using office add-ons (Javascript API)

I am currently in the process of developing an Office Add-in for Excel that requires the addition of a worksheet conditionally. I need to ensure that if the worksheet is not already present, it must be added and filled. If it already exists, I just need to ...

Troubleshooting issues with TypeScript D3 v4 module import functionality

As I embark on the journey of creating a miniature JS library using D3 to visualize line charts, I find myself navigating unfamiliar waters. However, I believe that deep diving into this project is the most effective way for me to learn. Below is the cont ...

What is the best way to arrange <div> elements with text inside without moving the text?

I need help figuring out how to stack one or more <div> elements on top of another <div> element while maintaining the text content within each. My issue is illustrated in this fiddle: https://jsfiddle.net/rd268ucy/1/. When attempting to drag o ...

Looking for a Javascript tool to select provinces graphically?

Looking for a graphic province selector similar to the one found on this website: . If anyone is aware of something like this, especially in the form of a jQuery plugin, that would be fantastic. Thank you. ...

Jquery Issue: Safari Leaves Alert Messages Unclosed When Opening Next Alert

I am experiencing an issue in Safari Browser and need some help with the following scenarios (with Example). When I click a button to delete an account, an alert message pops up. This alert window has two actions - "OK" and "Cancel". If I click "OK", it r ...

The full execution of Jquery show() does not pause until it finishes

Here is the sequence I want to achieve: Show a div element with the CSS class yellow Execute a function for about 5 seconds Remove the yellow class and add the green CSS class "state Ok" However, when running my code, the div container does not appear u ...

Extracting the id of an element using jQuery

The desired outcome is for the code to print the id of the selected div, but it's not working as expected. I've reviewed it multiple times but couldn't pinpoint the error. Any assistance would be greatly appreciated. Here is the HTML: < ...

Utilize morphTargets for ParticleSystem or PointCloud for enhanced visual effects

I currently have a project in Three.js version 65 where I am rendering a set of points at time t=0 in 3D space using ParticleSystem. I also have another set of points at time t=1. My goal is to animate the transition between these two sets of points simila ...

Access the style of the first script tag using document.getElementsByTagName('script')[0].style or simply refer to the style of the document body with document.body.style

Many individuals opt for: document.getElementsByTagName('script')[0].style While others prefer: document.body.style. Are there any notable differences between the two methods? EDIT: Here's an example using the first option: ...

Issues with Google Fonts failing to load correctly

Would you mind taking a look at this issue for me? In all browsers except Firefox, the expected behavior is that a web font remains invisible until fully loaded, preserving space on the page. Interestingly, in Chrome and IE9 (the browsers I tested), ther ...

The variable in the dataTables JavaScript is not receiving the latest updates

//update function $('#dataTable tbody').on('click', '.am-text-secondary', function() { //extract id from selected row var rowData = table.row($(this).parents('tr')).data(); var updateId = rowData.id; ...

Adjust the tooltip image alignment to be offset from the cursor and appear at the bottom of the page

After creating a code snippet for image tooltips on text hover, I encountered an issue on my website where the bottom of the page expanded to accommodate the images. Is there a simple way to align the cursor at the bottom of the image when scrolling to the ...

Is there a replacement for findIndex in Internet Explorer?

I am currently working on a code snippet for smooth navigation scroll to different sections. var lastId; var topMenu = $(".community-nav"); var topMenuHeight = topMenu.outerHeight() - 19; if(window.matchMedia("(max-width: 768px)").matches) ...

Can variables in JavaScript clash with input names in HTML?

I have the following code in an HTML file: <input type="..." name="myInput1" /> Then, in a JS file associated with this HTML file, I declare a variable to store the value of that input after it loses focus: var myInput1; Should I be concerned abo ...

Encountering the "excessive re-renders" issue when transferring data through React Context

React Context i18n Implementation i18n .use(initReactI18next) // passes i18n down to react-i18next .init({ resources: { en: { translation: translationsEn }, bn: { translation: translationsBn }, }, lng: "bn ...

Ways to conceal a div using jQuery when the video source is missing

If there is no source in the video, I want to hide the video_wrapper class <div class="video_wrapper" style="width: 100%; height: 100%; display: none;"> <video id="df-video" playsinline="" webkit-playsinline="" style="height: 100%; width: 100%; ...