Getting the mouse location with three.js: A step-by-step guide

Hey there, I'm currently working with IcosahedronGeometry. I've added CircleGeometry to each of its vertices. My goal now is to allow the circle to sense the mouse movement and follow it when it gets close. To achieve this, I've created a RingGeometry around the circle. If the mouse moves towards the ring, the circle should detect its position.

Unfortunately, I'm having trouble getting the exact mouse position using raycaster. Are there any other methods available to determine the mouse position accurately?

Answer №1

The Raycaster method is commonly used for this purpose:

mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
raycaster.setFromCamera( mouse.clone(), camera );
   
var items = raycaster.intersectObjects(scene.objects);

Visit this link for more details!

Answer №2

Below is a summary of the steps I took (certain parts have been omitted for conciseness):

// The concept of utilizing Raycaster was drawn from webgl_interactive_cubes.html in the THREE.js project examples directory
raycaster = new THREE.Raycaster();
mouse = new THREE.Vector2()
document.addEventListener('mousemove', onDocumentMouseMove, false);
window.addEventListener('resize', onWindowResize, false);
document.addEventListener('mousedown', onMouseDown, false);


function onDocumentMouseMove(event) {
    event.preventDefault();
    mouse.x = (event.clientX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
}

function onWindowResize() {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
}

function handleRaycasterIntersections(scene, camera) {
    camera.updateMatrixWorld();
    raycaster.setFromCamera(mouse, camera);
    var intersects = raycaster.intersectObjects(scene.children);

    if (intersects.length > 0) {

    } 
    else {

    }
}

function onMouseDown(event){
   customLog("mouse position: (" + mouse.x + ", "+ mouse.y + ")");
}

To view the complete code, refer to this link

Answer №3

Do you need code that tracks the cursor position on a web page?

let mouseX;
let mouseY;

document.onmousemove = function(e){
    mouseX = e.pageX;
    mouseY = e.pageY;
}

setInterval("checkCursorPosition()", 1000);
function checkCursorPosition(){
    alert("Cursor Position: " + mouseX + ", " + mouseY);
}

Answer №4

When your render is contained within a window or block with an absolute position, using window.innerWidth may result in incorrect coordinates. Additionally, attaching the mouse move event to the entire window can be inefficient.

A more effective approach would be:

const renderBlock = document.querySelector('#threeJSRenderWrapper');
let renderWidth = renderBlock.offsetWidth;
let renderHeight = renderBlock.offsetHeight;
const camera = new THREE.PerspectiveCamera(60, renderWidth / renderHeight, 0.01, 100000);

// This section can be placed inside the window resize function
camera.aspect = renderWidth / renderHeight;
camera.updateProjectionMatrix(); 
renderer.setSize( renderWidth, renderHeight );

const pointer = new THREE.Vector2();

renderBlock.addEventListener( 'pointermove', onPointerMove );

function onPointerMove( event ) {

    // Calculate pointer position in normalized device coordinates
    // (-1 to +1) for both components   
    pointer.x = ( event.layerX / renderWidth ) * 2 - 1;
    pointer.y = - ( event.layerY / renderHeight) * 2 + 1;
}

// Include remaining code for mouse intersection or other functionality

Using event.layerX and event.layerY will provide accurate coordinates relative to the block to which the mousemove event is attached.

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

Identify a div that manifests within the region of another element

Greetings everyone! I have a target that shoots randomly. I'm trying to make my "winner" div appear when a shot hits the center of the target. I really appreciate any help, I've already attempted collision detection but it doesn't work si ...

Emphasize user management and interaction in C# programming

In my master page, there is a user control (error control) that is initially hidden (visible set to false). When the submit button is clicked, I show the error control. After postback, I want to focus on this control. To achieve this, I am writing JavaScr ...

Having trouble with AngularJS integration in Node.js Express framework?

My AngularJS HTML file is below, and I am accessing it using http://localhost:3000/modulename/create. However, the issue arises as AngularJS is not functioning properly. For example, the ng-repeat directive is empty in the template, whereas when we console ...

Tips for dealing with event bubbling in React

Looking for a way to add an onBlur event to the left panel so that it closes when the user clicks on the right panel. I attempted using onMouseLeave but the closing animation isn't as smooth as desired. Additionally, I'd like for users to close t ...

Enhanced form updating in Laravel using real-time technology

Recently, I've been faced with the challenge of creating a dynamic page where users can freely input data. However, I'm struggling to figure out how to enable the page to save changes in real-time. The concept is that each time a user selects an ...

Could a javascript loop be created to continuously activate a button with each iteration?

I have just started learning javascript and I am in the process of creating a website where users can change the background by simply clicking on a button. It's working perfectly fine so far, but I want to add another feature where the background imag ...

Struggling to efficiently handle imported JSON data using VUE.JS JavaScript?

Struggling to extract specific information from JSON data that I need to import. Here is the sample data I'm working with: I am trying to extract details like the name, description, and professor for each entry. This is how I'm importing the d ...

Is there a way to prevent continuous repetition of JavaScript animated text?

I'm working on a code that displays letters and words one by one, but I can't figure out how to stop it from repeating. Can someone help me with this? <div id="changeText"></div> <script type="text/javascript"> var te ...

"Encountering an Issue with Storing Private Key as a String in NodeJS: Saving to .txt Results in Writing "[

Currently, I am attempting to save an EC key pair from the elliptic library as a string in a .txt file. However, when I do this, it ends up writing ""[object Object]"" to the file. UPDATE: Just wanted to note that the issue of turning the object ...

Troubleshooting problems with dynamic elements and qTip

On my page, I have an UpdatePanel where new forms are added when clicked. These new elements contain images that need to utilize qTip. This is the current setup: $(document).ready(function () { $('.ttip').qtip({ conten ...

How can I retrieve routing parameters in a Vue.js/Nuxt/TypeScript app?

In the process of developing my website based on the Nuxt TypeScript Starter template, I've encountered a challenge. Specifically, I have created a dynamically routed page named _id.vue within my pages folder and am looking to access the id property i ...

Troubleshooting issue with changing label text using innerHTML in JavaScript

In need of some advice regarding a javascript function I've been working on: function validateFile() { var file = document.getElementById('fuCSV'); if (file.value == "") { document.getElementById(&apo ...

What is the best way to retrieve a date (value) from a DatePicker and then set it as a property in an object

I am currently utilizing the react-datepicker library, and I have a question about how to retrieve a value from the DatePicker component and assign it to the date property within the Pick object. Extracting data from regular input fields was straightforw ...

Analyzing the HTML code retrieved from a jQuery AJAX call

My goal may appear straightforward: use HTML page retrieval with $.ajax() to extract a value from it. $(function () { $.ajax({ url: "/echo/html", dataType: "html", success: function (data) { $('#data').tex ...

The ng-click method on the checkbox input field in AngularJS is not being triggered

I'm trying to trigger a function in a toggle switch using ng-click, but the customerActiveDeactive function isn't being executed. <a title="Active/ Deactivate" > <input type="checkbox" class="js-switch" ng-init="status=True" ng-model ...

Can anyone provide guidance on extracting HTML elements from a stream of objects within rxjs?

In my Angular 8 project, I am working with a WordPress RSS feed to create a news scroller. The information from the feed is parsed into a JavaScript object using rss-parser from node.js. One of the challenges I am facing is extracting a HTTP link, an imag ...

Injecting JavaScript object values into dynamically generated modal

I have a JavaScript object that contains various training courses. Each category includes multiple training courses, and each course is associated with a specific category. Currently, I am able to display the title and description of each category in a mo ...

Remove any extra space from the fields before sending an Angular post request

I am looking for a way to eliminate all whitespace from three fields (leading, trailing, and between characters) before they are sent to the backend via an Angular post request. The data is coming from the form data object. Currently, I have managed to ach ...

Scrolling triggers Navbar Hover for all links

Currently, I am utilizing a free html5 theme as a foundation for a website project, but I require assistance with the Navbar Hover function. If you wish to see the original html5 theme, you can visit The theme was initially designed as a one-page layout, ...

Internet Explorer 10 is experiencing issues with attribute binding when it comes to click events

I'm currently working on an application and I'm experiencing some issues with IE 10. The captcha text displays correctly the first time, but when I try to refresh it by clicking the button, it doesn't seem to work. My guess is that there&apo ...