Obtaining Precise World Coordinates in Three.js with Renderer confined to a div instead of the entire window

Currently, I am utilizing the three.js framework and have set up the renderer within a div that occupies the right 50% of the screen with a height of 87.5%. My objective is to position a sphere at the exact spot where the user clicks, but I am encountering difficulties in accurately calculating the coordinates within this particular div. As a result, the spheres manifest in unpredictable locations far from the mouse pointer. How can I enhance the precision of coordinate calculation within this div? Any guidance or insights would be greatly appreciated. Below is the snippet of code for reference.

function onDocumentMouseMove( event ) {
    event.preventDefault();
    mouseX = (event.clientX / container.offsetWidth) * 2 - 1;
    mouseY = -(event.clientY / container.offsetHeight) * 2 - 1;
}

function onDocumentMouseDown(event){
    event.preventDefault()
    alert("X: " + mouseX + " Y: " + mouseY);
    var vector = new THREE.Vector3( mouseX, mouseY, 1 );
    var sphere = new THREE.Mesh(new THREE.SphereGeometry(size / 4), new THREE.MeshLambertMaterial(intensity));  
    sphere.position.x = vector.x;
    sphere.position.y = vector.y;
    sphere.position.z = vector.z;
    scene.add(sphere);
    spheres.push(sphere);
}

Answer №1

First things first, ensure that your camera is properly positioned within your div element:

camera = new THREE.PerspectiveCamera( 45, referenceToYourDiv.width / referenceToYourDiv.height, 1, 1000 );

Next, calculate the mouse event relative to the position of your div.

In THREE.js, the origin (0,0) is at the center of your container in 3D space, whereas in HTML, it is at the corner of your screen. You need to adjust for this difference by shifting the (0,0) point to the center of your container.

If you are working with fullscreen rendering, use this code:

mouseX = event.clientX - windowHalfWidth;
mouseY = event.clientY - windowHalfHeight;

For a custom size container, try the following calculation:

mouseX = (event.clientX - (window.innerWidth*0.5))-(container.width*0.5);
mouseY = (event.clientY - (window.innerHeight*0.875))-(container.height*0.5);

With a window width of 1920 and container width at 50%, these values will range from -480 to +480, centered around your container's width.

Similarly, with a window height of 1200 and container height at 87.5%, the values will range from -525 to +525, centered around your container's height.

This code should work theoretically, but it's always good to test it out for yourself.

Happy coding!

UPDATE: Check out this demo for a visual representation of what you're aiming for: http://jsfiddle.net/PwWbT/

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

Ways to convert all keys to uppercase in an array of objects?

Is there a way to capitalize the first letter of every key in an array of objects? I attempted to achieve this with the code below, but it's not working as expected. Any suggestions or corrections are appreciated. #current code function capitalizeO ...

What is the process for retrieving data on the server side using node.js that has been sent from the frontend via the post method

After diving into learning node.js with the express framework, I encountered a roadblock. I'm experimenting with a basic query search webapp and trying to send some data (a boolean named all) from front-end plain javascript via ajax to the server sid ...

The component is being updated, however the conditional statement is not functioning as expected

Having encountered an unexpected behavior in my react code, I'm seeking guidance as I am still fairly new to using react. Over the past few days, I successfully built a dashboard and now wish to implement a data page that includes CRUD transactions. ...

The datepicker calendar in UI Bootstrap fails to display the selected date in the input field

On my page, there is an option to edit a specific section by clicking on the "edit" button. This action opens a child view displaying all editable fields, including a datepicker bound to a modal. The issue arises when I try to select a date from the calen ...

Comparison Between Angular and Web API in Regards to Racing Condition with Databases

Currently, I am working on an Angular service that iterates through a list and makes web API calls to add or modify records in the database. The service operates on a small record set with a maximum of 10 records to update. After the loop completes, Angula ...

Conditionally defining variables in JavaScript only if they are currently undefined

I have been working on extracting two keywords from a URL in the following format: localhost:3000/"charactername"/"realmname" My goal is to extract "charactername" and "realmname" and assign them to variables. Here is the code snippet I am using: var c ...

Exploring the use of jQuery/JS for parsing and working with JSON

Hi everyone, I need some assistance with displaying data from an array created by a PHP file using JS/jQuery. Currently, I am working on implementing a points system for ZetaBoards which you can check out here. The points will be shown below the user' ...

What is the location within the Node.js event loop where microtasks are carried out and what is the order of priority for its phases

Discovering the inner workings of the Node event loop. ┌───────────────────────────┐ ┌─>│ timers │ │ └─────────────┬───── ...

Having trouble with the Semantic UI popup not showing div content correctly? Need to display table row data as well? Let's troub

Having trouble with this semantic-ui code popup error. Can anyone provide a solution? $(document).on('click', 'table td', function() { $(this) .popup({ popup: $('.custom.popup') }); }) ...

What is the best way to automatically update the contents of a div that contains PHP variables

Recently, I created a new page called queries.php <?php require("connection.inc.php"); $query = "SELECT SUM(john), SUM(robert), COUNT(school) FROM election"; $result = mysql_db_query($db, $query, $connection) or die("query error!"); $data = mysql_fetc ...

How come my ajax function is not processing when the form is submitted?

Having an issue with validating a form where I need to check if a username is available before submission. Although all functions, including the PHP script for checking the username, are working properly, I'm unable to prevent the form from submitting ...

Struggling to make jQuery code function properly in Wordpress, despite attempting to use noConflict

I have created a custom image grid gallery in WordPress using HTML and CSS, complete with popups and sliders. I had to code it myself because I couldn't find a suitable plugin that matched my design preferences. I have tested the functionality on my ...

Tips for resizing a 100% div without displaying vertical scrollbars in the browser

I am facing an issue with a table that has three rows. I have a main #container div with a height of 100%, and inside it is a table with 3 rows. The first and last row contain fixed size content. However, in the second row, there is a #content div with a h ...

Achieve validation of numerous variables without the need for a string of if-else

If we have three variables, such as firstName, lastName, and email, how can we check if they are empty or not without using multiple if else blocks? let firstName = "John"; let lastName = "Doe"; let email = "john.doe@example.com"; if (firstName.trim() == ...

The issue with THREE.js ORBITCONTROLLS not responding to changes in mouse button settings is causing inconvenience

Hey there, currently working on a project using THREE.js and I've run into an issue with my .mouseButtons functionality. var controls = new THREE.OrbitControls( camera, renderer.domElement ); controls.target.set( 0, 25, 0 ); c ...

Using Vue.js to process JSON data

My issue lies within this JSON data. I am trying to consume only the first element of the array using Vue.js 2 in order to display it. I was able to achieve this successfully using the console, but not with Vue.js. This line of code in the console works: ...

Enhance user experience by implementing a feature in AngularJS that highlights anchor

As I am in the process of developing a chat application using Angular, I have encountered an issue with switching between views. One view, named 'chat.html', displays the list of available users while another view, 'chatMessages.html', ...

Move the placement of a slice on a pie chart using Three.js

I have successfully created a pie chart object using 3js ExtrudeGeometry. However, my current goal is to move out a slice from the piechart object, similar to the illustration in the image below. https://i.sstatic.net/DRx7M.jpg Below is the code snippet ...

Tips for implementing the f11 effect with a delay of 5 seconds after pressing a key in JavaScript or jQuery

Is there a way to activate the F11 effect only 5 seconds after pressing a key using JavaScript or jQuery? ...

Enhancing Meteor functionality with the rubaxa:sortable package for sortable features

I am attempting to implement rubaxa:sortable in order to enable sorting of my list. client/helpers.js Template.getElements.helpers({ children: function() { return Articles.find({ parent: this._id }, {sort: {order: 1}}); } }); server/pub ...