Issue with ThreeJs raycaster not returning correct event.clientY value when header bar is visible

Here's the issue:

I'm trying to place a sphere on a 3D model when I click on it using ThreeJs raycaster. It works fine when the canvas covers the entire page, but if I add a header bar to the page, the positioning is off. Here are some visual examples:

Without the header bar, the sphere appears directly under the mouse pointer without any issues: a Ok

Now with the header bar; unfortunately, the sphere is positioned lower than the mouse pointer: a Ko

The problem also occurs when scrolling down the page, even without the header bar.

Below is the JavaScript code snippet for adding the sphere and handling event listeners:

function addSphere(coords, color) {

    sphere = new T.Mesh(sphereGeometry, sphereMaterial)

    sphere.position.set(coords.x, coords.y, coords.z)

    sphere.name = 'Sphere'

    scene.add(sphere)

}


function listeners() {

    document.addEventListener('resize', function() {

        var width = window.innerWidth
        var height = window.innerHeight

        camera.aspect = width / height
        camera.updateProjectionMatrix()
        renderer.setSize(width, height)

    }, false)


    container.addEventListener('click', function(e) {
        
        // Event handling logic here...

    }, false)

}

And here is the relevant part of index.html:

<!DOCTYPE html>
<html lang="fr">
<head>
    <!-- Page metadata and stylesheets -->

</head>
<body>

    <div id="header-bar" style="left: 0; right: 0; top: 0; height: 44px; line-height: 44px; text-align: center; font-size: 1.4em">Header bar</div>

    <div id="container"></div>

    <div id="buttons">
        <!-- Button elements -->
    </div>

    <!-- Three.js library imports and custom scripts -->

</body>
</html>

If you have an idea about what could be causing this issue, I would greatly appreciate your help. Thank you in advance!

Answer №1

The issue was resolved after deducting 44 units from e.clientY, taking into account the height of the header bar.

mouse.x = (e.clientX / width) * 2 - 1
mouse.y = - ((e.clientY - 44) / height) * 2 + 1

However, even after scrolling the page, the problem still remains unresolved.

Answer №2

@prisoner849 I appreciate your response, which directed me to the following resources:

&

Real mouse position in canvas

After implementing the code snippet provided:

function getMousePositionInCanvas(canvas, e) {

    var rect = canvas.getBoundingClientRect()
    return {
        x: e.clientX - rect.left,
        y: e.clientY - rect.top
    }

}


    var mousePosInCanvas = getMousePositionInCanvas(document.querySelector('canvas'), e)

    mouse.x = (mousePosInCanvas.x / width) * 2 - 1
    mouse.y = - (mousePosInCanvas.y / height) * 2 + 1

I'm thrilled to report that it performed flawlessly.

A sincere thank you!

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

Emphasize the close button within the popup window as soon as it appears

One of my coding challenges involves a div element, shown below: <div id="modal" tabindex="-1" ng-show="booleanvariable"></div> When the value of ng-show is true, this div is displayed. A "close" button located under the div should be focused ...

Select box failing to display default value

I am dealing with a specific data structure: $scope.personalityFields.traveller_type = [ {"id":1,"value":"Rude", "color":"red"}, {"id":2,"value":"Cordial", "color":"yellow"}, {"id":3,"value":"Very Friendly", "color":"green"}, ]; Also, there is a se ...

Unable to assign value to Ref data property in Vue3 due to undefined item

Recently, I've been utilizing Vue3 and Nuxt3 to work on a project. My main task involves extracting the :id parameter from the URL and checking if it matches an ID in a JSON file. If there is a match, I update a reference data point called 'exist ...

Creating personalized Stop and Play controls for Swiper.js Autoplay feature in a React/Next project

My quest to create a Swiper in React with autoplay functionality using Swiper.js has been quite a challenge. Despite following the instructions diligently and researching extensively, I couldn't find a solution. I even tried referencing a jQuery examp ...

Easily transform checkboxes into images using jQuery with no need for external plugins

Is it possible to replace checkboxes with images without using jQuery plugins? I'm hoping to achieve this in just a few lines of code. Thank you. ...

When the user clicks the back button in AngularJS

After searching extensively, I have yet to find a straightforward solution to my issue. The problem lies in a search/filter field that filters the page based on user input. While this filter works efficiently, it clears whenever a navigation item is clicke ...

The ExtJS Grid Filter is being triggered excessively

I am working on an ExtJS 6.2 grid that uses the 'classic' API. Although I am not very experienced with Ext, we have a grid component that we reuse with small modifications in different applications. In one of our apps, we have a text field for fi ...

JQuery - stylish vertical accordion navigation menu

I'm currently working on a vertical accordion-style sidebar navigation system. Everything seems to be functioning properly, but I've encountered some issues with the icons that I'm using from Twitter Bootstrap 3. You can view the code on th ...

Using dynamic, deferred loading of scripts in JavaScript

Is it necessary to create a reference for a dynamic, lazy import that is used multiple times in a script? For example, if there are 2 event handlers importing different functions from the same module: /* index.js */ window.addEventListener("click", (e) =&g ...

Firefox not responding to mouse movements

I am experimenting with creating an "animation" using JavaScript's "mousemove" Check it out here This is the code I am currently using $("body").mousemove(function(e){ var wWidth = $("body").width()/2 var wHeight = $("body").height()/2 var posX; v ...

What is the best way to securely transfer data from a Node/Express server to the client using JavaScript, ensuring sanitized HTML and preventing cross-site scripting (X

What is the best method to securely pass data from an Express backend to a client-side JavaScript in order to render it in the DOM using client-side rendering, while also allowing sanitized whitelist HTML and preventing XSS attacks? For example, if the No ...

Unable to dismiss message in Django

I'm a beginner in Django and I recently followed a tutorial to add message alerts to my code. The alerts are displaying correctly, but unfortunately, I am having trouble closing them using the 'x' button. https://i.stack.imgur.com/BQS1S.png ...

Incorporate information into a React component

I'm currently working on my initial react component and facing a challenge while adding items to the parent element through an external click event. The user needs to select from a list of search results, and I intend for these selections to be incorp ...

Guide on inserting HTML text box form input into Express route parameter

I'm currently working on implementing a feature that allows users to search through my mongo database using an endpoint structured like this: app.get('/search/:input', function(req, res){ console.log(`get request to: /members/${req.params ...

Executing a cross-site scripting (XSS) simulation within a MVC4 application on Visual Studio 201

Within my MVC 4 application, I am experimenting with simulating an XSS attack. The setup involves a button and a text box that simply outputs the entered value. However, when I input <script>alert('xss')</script> into the text box, an ...

Searching for columns should be at the top of an angular datatable, not at the bottom

In my Angular 7 project, I am utilizing the library found at this link. I have followed the example provided, which can be seen here. Everything is working perfectly, except for the position of the search columns. I would like the search columns to appear ...

Click event not functioning in programmatically loaded HTML

I am facing an issue with a JSON file that contains the page content I am trying to load. The link within it appears as follows: <a data-ng-click='foo()'>Bar</a> When I load this page content into the HTML page: <p class="body" ...

Unable to precisely reach the very bottom of the scrollbar

When trying to move to the bottom of the scrollbar, I seem to reach a bit higher than the actual bottom. https://i.stack.imgur.com/Vt83t.png Here is my code: ws.onmessage = function (event) { var log = document.getElementById('log') ...

Deleting JSON files using Discord and Node.js by requiring them from a specific folder

Currently, I am in the process of developing a Discord bot using Node.js. One of the functions within the bot utilizes JSON files to store information about specific entities. I aim to create a command in Discord that, when called with a specific name asso ...

Manifestation for JSON Firebug extension

In the process of developing a firebug extension, I encountered an issue with displaying JSON in the panel. Despite using a textarea to display the panel, the extension consistently crashes. Here is what I attempted: var template = domplate( { ...