Intersecting Rays and Positioning Spheres with three.js

I have a scenario where ray intersection is functioning properly with tube geometry. Upon ray intersection, a small red sphere and a tooltip appear next to the cursor. The image below shows the scene without a header:

When I include a header using a div element, the ray intersection still works but there is a noticeable distance between the red sphere, tooltip, and the mouse cursor. The image with the header is presented below:

Here is the code for the header, tooltip div, sphere, and collision detection function:

Header:

<div style="margin-top:10px;margin-left:3%;height:100px;width:70%">
  <label style="color:#b0bb02;font-size:14pt">three.js</label>
  <label style="color:#f5f7f9;font-size:14pt;font-weight:bold">Tube Geometry</label><br><br>               
</div>

Tool-tip div:

textDiv = document.createElement( 'div' );          
            textDiv.style.position = 'absolute';
            textDiv.style.top = '50px';
            textDiv.style.margin = '8px';
            textDiv.style.border = '1px solid blue';
            textDiv.style.zIndex = '100';
            textDiv.style.background = '#ffffff';
            textDiv.style.display = 'block';
            container.appendChild( textDiv );

Sphere geometry:

dot = new THREE.Mesh ( new THREE.SphereGeometry( 1, 12, 1 ), new THREE.MeshBasicMaterial( { color: 0xff0000 } ) );

Collision detection:

var intersects;
        
        function detectCollision(event){
            
            var vector = new THREE.Vector3(( event.clientX / window.innerWidth ) * 2 - 1,- ( event.clientY / window.innerHeight ) * 2 + 1, 0.5 );
            
            /*var mouse_x =   ((event.pageX-event.target.offsetParent.offsetLeft) / renderer.domElement.width) * 2 - 1;
            var mouse_y = - ((event.pageY-event.target.offsetParent.offsetTop) / renderer.domElement.height) * 2 + 1;
            var vector = new THREE.Vector3(mouse_x, mouse_y, 0.5);*/
                
                projector.unprojectVector( vector, camera );
                var ray = new THREE.Raycaster( camera.position, vector.subSelf( camera.position ).normalize() );

                intersects = ray.intersectObjects( objects );                                   
                
                var pnt=0; var clickedMD = 0; var clickedDegree; var clickedTVD;
                
                if ( intersects.length > 0 ) {                  
                                                                            
                    dot.position.copy( intersects[0].point );
                    scene.add( dot );
                    
                    var fi = intersects[0].faceIndex;
                    pnt = Math.round(fi/11);                    
                    
                    clickedMD = pathObjColl[pnt].md;
                    clickedTVD = Math.round(pathObjColl[pnt].point.z);
                    clickedDegree = degrees[Math.round(fi%11)]; 
                    
                    // tooltip
                    var elem = document.getElementsByTagName("canvas");
                    var canvas = elem[0];
                    var x = event.pageX - canvas.offsetLeft ;
                    var y = event.pageY - canvas.offsetTop  ;
                    //console.log("X: "+x+" Y: "+y);
                    textDiv.style.top = y+"px";
                    textDiv.style.left = x+"px";                
                    textDiv.innerHTML = "&nbsp;Degree: "+clickedDegree+"<br/>&nbsp;MD: "+clickedMD+" ft<br/>&nbsp;TVD: "+clickedTVD+" ft";
                    if(textDiv.style.display == 'none'){
                        textDiv.style.display = 'block';    
                    }
                }
                
                else if(intersects.length == 0){
                    var textDivVis = textDiv.style.display;
                    console.log(textDivVis);
                    if(textDivVis == 'block'){
                        textDiv.style.display = 'none'; 
                    }
                    
                }
            
        }

View demo on jsfiddle

What causes the discrepancy in the alignment between the mouse cursor, sphere, and tooltip when a header is added?

Answer №1

Is the textDiv positioned absolutely? Perhaps the header is causing a layout issue on the page and affecting the tooltip. Consider trying this:

textDiv.style.position = "absolute";

EDIT:

Actually, it seems that the header should be positioned absolutely instead. If not, it may disrupt the canvas and cause discrepancies between mouse positions in HTML and the webgl canvas.

Alternatively, if you prefer not to have the header overlap the canvas, you can adjust your mouse position calculation to account for the container position. For the Vector:

       var vector = new THREE.Vector3( 
                ( (event.pageX - container.offsetLeft) / window.innerWidth ) * 2 - 1, 
                - ( (event.pageY - container.offsetTop) / window.innerHeight ) * 2 + 1, 
                0.5 );

For the tooltip:

                textDiv.style.top = (container.offsetTop + y)+"px";
                textDiv.style.left = (container.offsetLeft + x)+"px";       

Updated jsFiddle: http://jsfiddle.net/tje8y/

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

Get started with the free plan for sails.js on Paas

Looking to test out my sails.js application deployment options. Can't seem to find sails.js on the supported list for Heroku and OpenShift's node.js offerings. Are there any free Platform as a Service (PaaS) plans available for sails.js? ...

Calculating the 3D Longitude and Latitude coordinates in a THREE.js globe using the radius along with the x and y values

Currently, I am exploring a Codepen where JSON data is being utilized to feed into a JavaScript application that maps coordinates using x and y values. Rather than utilizing longitude and latitude to map a location like Hong Kong, the developer uses these ...

What is the best way to display value in a dropdown option field using Laravel?

I am currently working with 3 tables: hosts, visitors, and visitor_types. My objective is to display the host name and visitor type in a drop-down option button. However, I find myself a bit perplexed when it comes to the controller and route code. I have ...

Updates to mousetrap key bindings are being reflected in the $scope object, but are not being detected by the

I have developed a function that updates a scope variable as shown below: // controller.js $scope.variable = 0; $scope.$watch('variable', function(){ console.log("change from watch"); }); $scope.increment = function(){ $scope.variable++; ...

The $route object in vue-router appears to be empty when used with single file components

I am facing an issue while using single file components with vue-router and vue-2.0. The problem I can't seem to resolve is that the this.$route object, when called from a component, always returns empty values. For example: https://i.sstatic.net/ws ...

Ways to send a variable to a component through history.replace

Is there a way to retrieve the match.chatroomId in a functional component? I am currently using history.replace to navigate to this component. Here is the code snippet: onClick = {() => history.replace(`/chat/${match.chatroomId}`)} ...

Tips for transferring a column in an array to an object field within an array

I have a piece of code where I need to pass values from the 'dataList' array into this.data object's 'labels' and 'datasets'-> data. When I try to directly set the values, I get an undefined result. So I created a var ...

Showing information retrieved from an API and rendering it on an HTML page

My aim is to showcase a list of calculated results fetched from a local server. In the console, this data appears as an array of objects, but on the webpage, it is being displayed as separate string characters for each li element. How can I display the con ...

The content in tinymce cannot be edited or removed

Is there a method to prevent certain content within the tinyMCE Editor from being edited or removed? While I know that adding a class "mceNonEditable" can make a div non-editable, it can still be deleted. Is there a way to make it unremovable as well? ...

Don't give up on the entire task just because one promise was rejected

To handle multiple promises in redux saga, you can use the all function (equivalent to Promise.all): yield all( users.map((user) => call(signUser, user)), ); function* signUser() { yield call(someApi); yield put(someSuccessAction); } An issue ...

What is the best method to assign values to AngularJS controller variables using Python Selenium or the JavaScript console?

After utilizing Python Selenium and AngularJS for a few months, I am currently attempting to adjust certain AngJS variables (specifically the aslider filter from here) and refresh the page in order to extract some data. Below is the code I am using for thi ...

The appearance of the check box remains stagnant visually

Having trouble with dynamically changing the state of a checkbox based on a database value. Even though the value changes after a button click, the visual state of the checkbox remains the same. Here is the link to the JSFiddle for testing: http://jsfiddle ...

What is the best way to center the startIcon material ui icon?

I'm having trouble keeping the icon button centered on my page. When I add left: "0.5rem" to the sx prop, it ends up pushing the button icon even further away from center. I'd prefer not to use makeStyles to manually override the position. Any ad ...

Having trouble grasping the error message "Uncaught Typerror Cannot Read Property of 0 Undefinded"?

As I embark on creating my very first ReactJS website with Node in the back-end, I encountered an issue in fetching and printing data. While I successfully displayed the names, pictures, and emails of project members from the server, I faced an error when ...

Uncertainty about the integration of a JavaScript file into a PHP file

Having two PHP files where one is executed through a URL and makes AJAX calls to the second PHP file can present challenges. Sometimes, the AJAX results return HTML content with JavaScript events that do not work as expected. To solve this issue, I have in ...

Using Javascript's regular expressions to add double quotes around JSON values that are not already enclosed in quotes

Dealing with improperly formatted JSON values can be a challenge. The response I am working with is from a Java Servlet, specifically a hashmap, over which I have no control. Initially, it looked like this: { response={ type=000, products=[{id=1,name=prod ...

Ways to eliminate HTML elements from one HTML content to another

The HTML code provided is as follows: <dl class="item-options"> <dd class="truncated" style="color:red;">DSOX3000-232, RS232/UART Serial Decode and Trigger - in <a onclick="return false" class="dots" href="#">...</a>/&l ...

Error encountered while attempting to install material-ui v3.0.3 due to an unexpected termination of the JSON input

I'm currently in the process of installing the most recent stable version of material-ui(v3.03) by running: npm install @material-ui/core. However, I encountered an issue with npm ERR! Unexpected end of JSON input while parsing near '...-/brcast- ...

My attempts to integrate PHP into jQuery tabs have been unsuccessful

My code seems to be acting strangely, as the PHP code I originally entered in tab 2 has somehow escaped that tab and spread into all the other tabs. This means it is visible in multiple tabs instead of just one. The purpose of this PHP code is to retrieve ...

Issue with custom cursor not functioning properly when hovering over hyperlinks

I'm currently developing a website and I've created a custom cursor to replace the default one. The custom cursor is detecting mouse movement, but it's not interacting with hyperlinks. Below is the code I'm using. HTML <div class=& ...