The triggering of mouse events on 3D spheres in THREE.js does not occur accurately in the specified location

I've taken over a project from someone else and it's actually pretty cool. The goal is to create a dynamic diagram with nodes (spheres) that can be clicked on to reveal related nodes in a new diagram.

Right now, I'm focusing on the clickable functionality which is turning out to be more challenging than I anticipated. I've been delving into raycasting and vectors, and I've come across some examples that are close to what I'm aiming for:

However, when hovering near the nodes, they change color unexpectedly and the "hotspots" where the mouse should intersect with the nodes seem random, as indicated in the image provided. I believe I'm lacking some understanding of the unprojecting/converting/transformation from 3d to 2d. This might be the reason why my mouse isn't properly interacting with the nodes on the screen.

Here is my onmousemove event:

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

        var canvasSvg= d3.select("#canvas-svg")[0][0];          
        mouse.x = ( event.clientX /  canvasSvg.clientWidth) * 2 - 1;
        mouse.y = - ( event.clientY / canvasSvg.clientHeight ) * 2 + 1;

        var vector = new THREE.Vector3(mouse.x, mouse.y, 1).unproject(camera);

        raycaster.set(camera.position, vector.sub(camera.position).normalize());

        var intersects = raycaster.intersectObjects( scene.children ); 

        // console logs
        console.log("current 'canvas' div");
        console.log(canvasSvg)

        console.log("mouse");
        console.log(mouse);

        console.log("vector");
        console.log(vector);



        if ( intersects.length > 0 ) {
            intersects[0].object.material.color.setHex( Math.random() * 0xffffff ); 
            intersects[0].object.callback(); 
        }

        for ( var i in intersects ) {
                intersects[ i ].object.material.color.setHex( Math.random() * 0xffffff | 0x80000000 );
        }       
    }

Here is a snippet about my camera:

        // Set camera attributes and create camera
    var VIEW_ANGLE = 7, //field of view
        ASPECT = WIDTH / HEIGHT, 
        NEAR = 0.1,
        FAR = 10000;
    var camera = new THREE.PerspectiveCamera(VIEW_ANGLE, ASPECT, NEAR, FAR);

https://i.sstatic.net/KIvCK.png

Answer №1

Hey there! Just wanted to share how I was able to resolve the issue with this particular solution: http://jsfiddle.net/fek9ddg5/62/

    By recalculating the mouse coordinates based on the offset of the renderer element, the ray projection issue was successfully fixed.
    Here's the code snippet that did the trick:

It turns out, the confusion stemmed from the ray not knowing exactly where to be projected. Once I factored in the offset from the top of the screen to the canvas, everything fell into place.

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

Struggling to successfully update a database using a combination of javascript and PHP

I have been attempting to update a database by utilizing JavaScript and PHP. Below is the code from my index.html: <!DOCTYPE html> <html> <head> <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.3.min.js"> ...

Using NextJS to render a Link component by creating an element

Struggling to use createElement in NextJS to render a Link, but facing issues. Code: import {createElement} from "react"; import Link from "next/link"; createElement( item.href ? Link : "div", { href: item.hre ...

What is the best approach to reverse the selection of <li> elements by utilizing :not() and :contains

I am looking to implement a live search feature using jQuery. Below is the code snippet I have written: $("#searchInput").on("keyup", function () { var searchTerm = $("#searchInput").val(); $('li:contains("' + searchTerm + ' ...

Modify the properties of the following bdi element that contains text using JQuery

I am not a tech expert, but I have created a script and am running it on a website using Tampermonkey. Website code:- <div id="__grid1-wrapperfor-__label44" class="sapUiRespGridSpanL1 sapUiRespGridSpanM3 sapUiRespGridSpanS6 sapUiRespGridS ...

Execute a function only once when using it in conjunction with ng-repeat in AngularJS

I need a way to ensure that a specific function is only called once when used in conjunction with ng-if and ng-repeat. <td ng-if="!vm.monthView && vm.yearView=='contract-year'" nginit="vm.ContractYearBaselines()" class="baseline-data ...

Using Angular's filter service within a controller

Just starting out so please be kind!! Encountering an issue with Angular 1.3 while using a Stateful Filter within a controller. In brief, when utilizing the $filter('custom')(data) method instead of the {{ data | custom }} method - and the cust ...

The functionality of anchor links created through ajax is not operating correctly

Issue: I am encountering a problem where I have a table filled via Ajax, containing local anchors. When an anchor is clicked, it should make a section visible and automatically scroll to it. This functionality works when manually filling the table, but not ...

Exploring the variable scope in Node.js with a focus on separating routes

My routing configurations are stored in an external folder. Find them in the ./routes directory This is how I set up my routes within the server.js file: app.get('/', routes.index); app.post('/validation', register.valid); The reg ...

Is it possible that the images are unable to load on the page

The frontend code successfully retrieves the image links sent by the backend but encounters issues displaying them. Despite confirming that the imgUrl data is successfully fetched without any hotlink protection problems, the images are still not appearing ...

The functionality of the dynamic text box is disrupted when a form element is added

I am in the process of developing a form and am looking to create dynamic text boxes using Bootstrap. The code that I have currently works as expected: $(function() { $(document).on('click', '.btn-add', function(e) { e.preventD ...

Exploring the wonders of accessing POST request body in an Express server using TypeScript and Webpack

I am currently working on a Node and Express web server setup that utilizes Webpack, along with babel-loader and ts-loader. Let's take a look at some key portions of the code: webpack-config.js: const path = require("path"); const nodeExte ...

What is the best way to assign a unique color to each circle?

Struggling to assign random colors to each circle in my canvas. Currently, they all have the same color that changes upon refresh. I'm aiming for unique colors on each circle but my attempts have been unsuccessful so far. Check out my code below: v ...

Oops! The requested page "/api/auth/[...nextauth]" is missing the necessary "generateStaticParams()" function, thus making it incompatible with the "output: export" configuration

Currently, I am working on a Next.js project where I have successfully implemented user authentication using next-auth with the Google Provider. However, while attempting to build the project, an error is being thrown by the compiler stating: "Error: Page ...

Does Next.js pre-render every page, or does it only pre-render the initial page?

As I dive into the world of nextjs, I'm coming across conflicting information. Some sources claim that nextjs only prerenders the first page, while others suggest that all pages are prerendered by default. This contradiction has left me confused about ...

Tips for adjusting HighCharts layout with highcharts-vue integrations

I have a fairly simple component: <template> <div> <chart v-if="!loading" ref="priceGraph" constructor-type="stockChart" :options="chartData" ...

What could be causing my div to not appear when using jquery's show function?

I'm dealing with HTML code that looks like this: <div id="answerTypeSection" style="visibility: hidden"> <div class="row"> <div class="col-md-2">adfadfafasdfasdfas</div> </div> <label class="control-label"&g ...

Error encountered: Multer TypeError - fields does not have a function called forEach

I'm currently working on a metadata reader using multer in node.js with express on c9. I've spent some time searching for solutions to my issue, but it seems like no one else has encountered the error I am facing: TypeError: fields.forEach is no ...

What are the benefits of using .factory instead of declaring a variable in AngularJS?

As I delve into learning Javascript and Angular JS, I'm exploring alternative approaches to using .factory. Instead of declaring what it returns as a variable and referencing it, I'm curious if there's a way around using factory. Why is fac ...

Stopping the loop: Disabling the SetInterval function with ResponsiveVoice code in JavaScript

Currently, I am developing a queuing system and implementing voice announcements using Responsive Voice. I have used setInterval, but the issue is that the voice keeps looping without stopping. $( document ).ready(function() { setInterval(function() ...

What is the best way to determine if an item qualifies as an Angular $q promise?

In my project, I have an existing API library that is not Angular-based. This library contains a method called .request which returns promises using jQuery.Deferred. To integrate this with Angular, I created a simple service that wraps the .request method ...