The Three.js Raycaster gets thrown off when scrolling through the page

When a scene does not display entirely on the page and you can scroll, the Raycaster stops working and is affected by the scrolling offset.

If you scroll to the side by 20 pixels down, you need to have 20 pixels below the object for the click to be recognized correctly by the Raycaster.

What is the solution to this problem?

I would greatly appreciate any help. Thank you!

Answer №1

Implement the following code snippet for optimal results:

var rect = renderer.domElement.getBoundingClientRect();
mouse.x = ( ( event.clientX - rect.left ) / ( rect.width - rect.left ) ) * 2 - 1;
mouse.y = - ( ( event.clientY - rect.top ) / ( rect.bottom - rect.top) ) * 2 + 1;

This solution will be effective for your needs. To see a demonstration, scroll to the bottom and click on the cube.

<!DOCTYPE html>
<html>
<head>
<script src="http://threejs.org/build/three.min.js"></script>

    <link rel="stylesheet" href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" />


<style>
body {
    font-family: Monospace;
    background-color: #fff;
    margin: 0px;
}

#canvas {
    background-color: #000;
    width: 200px;
    height: 200px;
    border: 1px solid black;
    margin: 10px;
    padding: 0px;
    top: 10px;
    left: 100px;
}

.border {
    padding:10px; 
    margin:10px;
height:3000px;
overflow:scroll;
}

</style>
</head>
<body>
<div class="border">
  <div style="min-height:1000px;"></div>
<div class="border">
<div id="canvas"></div>
</div>
</div>
<script>
// Three.js ray.intersects with offset canvas

var container, camera, scene, renderer, mesh,

    objects = [],
    
    count = 0,

    CANVAS_WIDTH = 200,
    CANVAS_HEIGHT = 200;

// Remaining code from the original source goes here...

</script>
</body>
</html>

Answer №2

Kris Roofe's solution solved my issue, all I needed to do was adjust the mouse.x value.

mouse.x = ( ( event.clientX - rect.left ) / ( rect.right - rect.left ) ) * 2 - 1;

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

Passing a callback function through a prop in Vue.js

Currently, I have a component structured in the following way: <template> <div> <pagination class="center" :pagination="pagination" :callback="loadData" :options="paginationOptions"></pagination> </div> </t ...

What is the best way to refresh or render a list in a React application?

While attempting to update the calendar days by using useState, I encountered a "too many re-renders" error. Even though the list was updated correctly, the component did not render on the screen as expected. I am struggling with figuring out how to update ...

trigger a function when the iframe is altered

I am currently working on creating a function that can process credit card payments using an iframe. The challenge I am facing at the moment is dealing with error messages appearing in a less than ideal manner. Photo: I have been attempting to capture the ...

Setting Up AdminLTE Using Bower

Recently, I decided to incorporate the Admin LTE Template into my Laravel project. I diligently followed the guidelines outlined here As soon as I entered the command: bower install admin-lte The installation process seemed to start, but then the ...

Tips for using Chrome Dev Tools to troubleshoot JavaScript code embedded in a webpage

Currently, I am deeply involved in a project at my workplace where I am tasked with fixing tickets and debugging issues. I have reached a point where I need to understand what values the Javascript code is returning. Here's the problem I am facing: ...

Tips for implementing a CSS style alteration upon clicking a button in a separate HTML page

I created JavaScript quizzes for my users to complete. Once they click the finished button at the end of the quiz, I want to highlight the box on the home page with a green outline to indicate completion. The complete button is located on the challenge1.ht ...

Is there a way to exclude certain URLs from the service worker scope in a create react app, without the need to eject from the project?

Is there a way to remove certain URLs from a service worker scope in create-react-app without needing to eject? The service worker is automatically generated, and it seems impossible to modify this behavior without undergoing the ejection process. ...

Trigger the select dropdown when a key is clicked

I am currently working on a project in react where I am utilizing the Select component from material. When I open the dropdown and press a key on my keyboard, the option starting with that key gets automatically selected. This behavior is also observed in ...

The error occurring in the React app is a result of the page rendering prior to the API data being fetched

Utilizing the following component for my Nav, I aim to showcase the current weather based on the user's location. However, an issue arises as the page is being rendered before retrieving data from the openWeather API. import React, { useState, useEffe ...

Attempting to assign the object retrieved from the interface as the new value for window.location.href

I encountered an issue where the error message Type MyInterface' is not assignable to type 'string' popped up. Although I comprehend the problem, finding a suitable solution has proven to be challenging. MyInterface solely returns one item, ...

Accepting parameters in an Express POST requestWondering how to accept parameters in

Currently, I have an API that requires passing car make, model, and year in the URL. Using an express router post call, I am able to retrieve the query parameters and set them to an object. I need to ensure that the URL can accept parameters like this: lo ...

The type '{}' cannot be assigned to type '() =>'

Do you have a TypeScript question? I am curious about how to 'specify' a single object in useState using the incoming properties of id, heading, and text with an interface or similar method. Take a look at the code snippet below: import React, ...

Is it possible to embed PHP code within HTML?

Can you identify any issues in the code below? Everything works fine when I remove the PHP variable $var, but I actually need to insert a value of 5000 into it. echo '<div id="img1" style="position:absolute;left:81px;top:127px;width:12px;height:12 ...

Looking for guidance on sending data from a JS file to HTML using Nodejs? Seeking advice on various modules to achieve this task effectively? Let's

Looking for advice on the most effective method to transfer data from a JS file (retrieved from an sqlite db) to an HTML file in order to showcase it in a searchable table. My platform of choice is NodeJS. As a beginner, I am willing to put in extra time a ...

Guide to making a toggle button with a Light/Dark mode functionality

I have implemented a light/dark toggle button and now I want to integrate the functionality for switching between light and dark themes on my webpage. The switch should toggle the theme between dark and light modes when clicked. Some basic styling has been ...

Chart rendering failure: unable to obtain context from the provided item

I am encountering an issue while trying to incorporate a chart from the charts.js library into my Vue.js and Vuetify application. The error message that keeps popping up is: Failed to create chart: can't acquire context from the given item Even af ...

There was an issue with locating the module: Error: Unable to find the specified module 'vue-axios' in the directory 'C:xampphtdocsvue-laravel-api esourcesjs'

I am currently working on a CRUD project using Laravel and Vue.js. I made sure to install all the necessary devDependencies, but when I try running NPM run watch, I encounter the following error: https://i.sstatic.net/Kqkpq.png My app.js file includes all ...

Boost your website's loading time by utilizing the async and defer attributes

Looking to enhance the speed of my webpage, particularly focusing on improving initial page speed. Research suggests that using the async and defer attributes for JavaScript can be beneficial. All JavaScript scripts are currently placed just above the cl ...

Having trouble retrieving directive parameters in Vue.js?

Vue.directive('customselect', { params: ['selectedTask'], bind: function () { var that = this; $(this.el) .select2() .on('change', function () { that.set(this.value); if (!this.name.matc ...

Sync your data effortlessly with jQuery Datalink, the ultimate solution for

While experimenting with the jQuery Data linking proposal by Microsoft, I came across an unexpected discovery. There seems to be an additional property present in my objects, and I am curious as to why it is there. Initially, I thought it was a mistake on ...