Obtaining Mouse Click X, Y, and Z Coordinates with Three.js

I am currently utilizing version 68 of three.js.

My objective is to gather the X, Y, and Z coordinates upon clicking somewhere on the canvas. Despite following the steps outlined in this guide, I am encountering a consistent Z value of 0: Mouse / Canvas X, Y to Three.js World X, Y, Z

The main idea is that when clicking within the scene where a mesh exists, the intention is to calculate the position values resembling that of the mesh itself. Please note that this scenario serves solely as an example. While I acknowledge the option of using raycasting by checking for collisions with meshes and examining their positions, my preference is for a method that functions seamlessly even without direct interaction with a mesh.

Is such functionality feasible? Referencing the provided jsfiddle: http://jsfiddle.net/j9ydgyL3/

In the aforementioned jsfiddle, targeting the center of the square should ideally yield X, Y, and Z values of 10, 10, and 10 respectively, mirroring the coordinates of the square's position. Delving into the following key functions:

function getMousePosition(clientX, clientY) {
    var mouse2D = new THREE.Vector3();
    var mouse3D = new THREE.Vector3();
    mouse2D.x = (clientX / window.innerWidth) * 2 - 1;
    mouse2D.y = -(clientY / window.innerHeight) * 2 + 1;
    mouse2D.z = 0.5;
    mouse3D = projector.unprojectVector(mouse2D.clone(), camera);
    return mouse3D;
}

function onDocumentMouseUp(event) {
    event.preventDefault();

    var mouse3D = getMousePosition(event.clientX, event.clientY);
    console.log(mouse3D.x + ' ' + mouse3D.y + ' ' + mouse3D.z);
}

A portion of alternative code attempts remains commented out. It's worth noting that these commented segments didn't achieve the desired outcome in the jsfiddle environment, potentially due to the utilization of version 54 of three.js. Conversely, everything operates smoothly on my end with the upgraded version 68.

Edit: To emphasize, my goal is to obtain the coordinates regardless of the cursor's location. While a mesh was employed in this demonstration for simplicity, allowing verification by aligning calculated coordinates with those of the mesh, the ultimate aim is to function sans reliance on raycasting toward a mesh. For instance, having real-time display of calculated coordinates on the console irrespective of the scene's elements would be ideal.

Answer №1

To achieve this, utilizing a THREE.Raycaster is recommended. By specifying a list of intersectObjects, you can obtain an array of objects that have intersected with the ray. Consequently, extracting the position from the selected object in the returned list is feasible. View the revised fiddle here. I have also updated your Three.js to version R68

For more intricate usage of THREE.RayCaster, explore the examples on Threejs.org/examples such as this interactive cubes example.

Highlighted code snippet from the revised fiddle:

function getMousePosition(clientX, clientY) {
    var mouse2D = new THREE.Vector3();
    var mouse3D = new THREE.Vector3();
    mouse2D.x = (clientX / window.innerWidth) * 2 - 1;
    mouse2D.y = -(clientY / window.innerHeight) * 2 + 1;
    mouse2D.z = 0.5;
    mouse3D = projector.unprojectVector(mouse2D.clone(), camera);
    return mouse3D;
    var vector = new THREE.Vector3(
    (clientX / window.innerWidth) * 2 - 1, -(clientY / window.innerHeight) * 2 + 1,
    0.5);

    projector.unprojectVector(vector, camera);
    var dir = vector.sub(camera.position).normalize();
    var distance = -camera.position.z / dir.z;
    var pos = camera.position.clone().add(dir.multiplyScalar(distance));
    return pos;
}

function onDocumentMouseUp(event) {
    event.preventDefault();

    var mouse3D = getMousePosition(event.clientX, event.clientY);
    console.log(mouse3D.x + ' ' + mouse3D.y + ' ' + mouse3D.z);

var vector = new THREE.Vector3( mouse3D.x, mouse3D.y, 1 );    
    raycaster.set( camera.position, vector.sub( camera.position ).normalize() );

    var intersects = raycaster.intersectObjects(scene.children );
    if(intersects.length > 0){
        console.log(intersects[0].object.position);
    }
}

function animate() {
    requestAnimationFrame(animate);
    render();
}

function render() {
    renderer.render(scene, camera);
}

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

Converting coordinates to pixel-based fixed positioning in CSS

After creating an animated square pie chart using basic CSS to display it in a grid format, I am now looking to transform the larger squares into a state map grid. Any ideas on how to achieve this? In my JavaScript code snippet below, I believe there is a ...

Connect a responsive div to a main div

I'm relatively new to the world of Javascript, CSS, and HTML. Currently, I'm attempting to anchor a div to the center and bottom of its parent div. The parent div contains a responsive background image and my fa fa-arrow icon is correctly positi ...

Slider MIA - Where Did it Go?

I'm having an issue with my slider. When I load the page, it doesn't show the first image until I click the button to load it. How can I make it display the first image by default? Below is my JavaScript code: <script> var slideIndex = 1 ...

Accessing a service instance within the $rootScope.$on function in Angular

I'm looking for a way to access the service instance variable inside the $rootScope in the following code. myapp.service('myservice',function($rootScope) { this.var = false; $rootScope.$on('channel',function(e,msg) { v ...

Send the chosen value from a dropdown menu to a PHP script

<style type="text/css"> form select { display:none; } form select.active { display:block; } </style> <script type="text/javascript"> window.onload = function () { var allElem = document. ...

The loading of charts and animations is sluggish on mobile devices

My Chart.js chart starts with 0 values and updates upon clicking submit to load data from an external database. While this works efficiently on a computer browser, the load time is significantly longer when accessing the page on a mobile device. It takes a ...

Integrating array elements into the keys and values of an object

Given the array below: const Array = ['Michael', 'student', 'John', 'cop', 'Julia', 'actress'] How can I transform it into an object like this? const Object = { Michael: student, John: cop, Juli ...

Retrieving data from an XML file using an Ajax request

I am using a native AJAX request to insert node values into HTML divs. However, I have noticed that when I update the XML values and upload them to the server while the website is running, Chrome and IE do not immediately reflect the changes (even after re ...

Javascript promises executing in a mixed-up sequence

Utilizing Javascript's native Promise, I created a modified version of fs.readFile called readFileAsync. This function reads and parses a JSON file, returning the object when resolving. function readFileAsync(file, options) { return new Promise(fun ...

Gradually fade with JavaScript

My JavaScript code below is used to recursively reload a specific DIV with the results of a data query. The issue I'm facing is that each time the DIV, identified by id="outPut", is reloaded, all the data fades in and out due to the fadeTo function. ...

Adding Empty Space Following Error Message in Codeigniter

I am encountering an issue with my code where there is a blank space appearing after the error message. Here is the code snippet that is causing the problem: <script> const successNotification = window.createNotification({ theme: 'error&a ...

AngularJS Datepicker - calendar dropdown does not update when the model changes

I've been facing a challenge with the AngularJs datepicker in my project for some time now. Within my application, users have the option to either manually select a date using the calendar or click on "This Month" to automatically set the date to the ...

Preventing users from copying and pasting information from my form by implementing javascript restrictions

I'm looking for a solution to prevent users from copying and pasting in my form using JavaScript. I want to restrict the ability to paste or copy any content into the form. Any assistance would be greatly appreciated! ...

Opera's compatibility with jQuery's Append method allows developers to

I recently wrote a jQuery script that interacts with a JSON feed and dynamically creates HTML code which is then added to a designated div on my WordPress site. Surprisingly, the functionality works flawlessly in all browsers except for Opera - where not ...

Issue with conflicting trigger events for clicking and watching sequences in input text boxes and checkboxes within an AngularJS application

When creating a watch on Text box and Check box models to call a custom-defined function, I want to avoid calling the function during the initial loading of data. To achieve this, I am using a 'needwatch' flag inside the watch to determine when t ...

Adding a CSS link to the header using JavaScript/jQuery

Is there a way to dynamically inject a CSS link located in the middle of an HTML page into the head using JavaScript? <head> ... styles here </head> <body> code <link href='http://fonts.googleapis.com/css?family=Lato:400,300, ...

What is the process for implementing JavaScript in Django?

I'm a newcomer to this and although I've tried searching on Google, I haven't found a solution. I'm facing an issue where I can include JavaScript within the HTML file, but it doesn't work when I try to separate it into its own fil ...

Non-responsive behavior triggered by a button click event (JavaScript)

Help needed with displaying results on the same page for an online calculator I'm creating. Why are the results not showing up as expected? I want users to input 4 pieces of information, have the logic executed, and then display the answers below th ...

I possess an array of objects that includes both images and documents. My goal is to examine the mime_type of each object and select the first element in React to be displayed within an <img> tag

I have an array of objects that contain images and documents. My goal is to display the first image only if the mime_type is 'image/jpeg' or 'image/png'. I am working with React. Despite my attempts, I keep encountering undefined resul ...

How to retrieve specific items from an array contained within an array of objects using Express.js and MongoDB

Within the users array, there is an array of friends. I am looking to retrieve all friends of a specific user based on their email where the approved field is set to true. In my Node.js application, I have defined a user schema in MongoDB: const UserSchem ...