Experiencing trouble with detecting intersections using the Three.js raycaster

After successfully writing a code to intersect some objects, I encountered an issue when adding a canvas along with other div elements in the HTML document. Now, there seems to be no intersection on the object. You can observe this live example here. If you select the button "cross" at the top right and try to move the shape, you'll notice that it doesn't work properly unless you place your mouse slightly to the right of the shape. The intersection is completely off. Despite trying solutions from Stackoverflow, nothing seems to fix the issue. Any help or insights would be greatly appreciated as I am quite desperate.

To see how it should work, check out this other live example: . Even after attempting different solutions suggested on Stackoverflow, the problem persists.

One possibility could be related to the mouse coordinates:

mouse2D.x = ( ( event.clientX - renderer.domElement.offsetLeft ) / renderer.domElement.width ) * 2 - 1;
mouse2D.y = - ( ( event.clientY - renderer.domElement.offsetTop ) / renderer.domElement.height ) * 2 + 1;

You can view the javascript code here.

Another factor to consider might be:

I've noticed two different dimensions for the canvas, as shown in this screenshot:

Answer №1

When working with event.clientX in your code, keep in mind that it is relative to the browser window, not the canvas itself. To get the offset relative to the canvas, you will need to calculate it based on the elements containing the canvas.

This helpful snippet of code can assist you in achieving the desired outcome:

I rely on this code whenever I encounter a situation involving mouse interactions over a canvas element.

If you provide a simpler test scenario, I would be happy to create a solution for you.

Answer №2

Consider making the following adjustments to a piece of code:

let x = event.offsetX === undefined ? event.layerX : event.offsetX;
let y = event.offsetY === undefined ? event.layerY : event.offsetY;

mouse2D.x = (x / renderer.domElement.width) * 2 - 1;
mouse2D.y = -(y / renderer.domElement.height) * 2 + 1;

Answer №3

Within your Document Object Model (DOM), the canvas element is represented as:

<canvas width="1139" height="975"></canvas>

This is where your script retrieves the height and width values.

However, the actual dimensions of the canvas are determined by the following CSS properties:

width: 100%;
height: 100%;

To avoid any conflicts, it's recommended to remove one of these sets of dimensions so that the scripting can accurately access the correct values.

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

Angular Directive - introducing a fresh approach to two-way binding and enable "pass-by-value" functionality

In a previous question, I inquired about the possibility of incorporating an attribute on a directive to allow for values to be passed in various formats, such as: <my-directive att> //Evaluates to true <my-directive att="true"> ...

Having trouble with Npx and npm commands not running in the VSCode terminal?

I am currently facing an issue while attempting to set up a react app in vscode using the command npx create-react-app my-app. It seems like the command is not working properly. Can anyone provide guidance on what steps I should take next? Despite watchin ...

Creating TypeScript Classes - Defining a Collection of Objects as a Class Property

I'm trying to figure out the best approach for declaring an array of objects as a property in TypeScript when defining a class. I need this for a form that will contain an unspecified number of checkboxes in an Angular Template-Driven form. Should I ...

Validation of phone numbers based on country codes

How can I validate phone numbers based on the selected country in Angular? Are there any Angular packages specifically for this task? I've attempted to use regex, but it only works for certain countries. I need a solution that can validate mobile an ...

AngularJS - Calculate multiple currencies

I need to calculate the product of a value and months. For the input value, I am utilizing a Jquery Plugin to apply a currency mask. Unfortunately, the calculations are not functioning properly with this plugin. My goal is to multiply the value, includin ...

Add a new item to an array in Angular 2 when a click event occurs

I'm trying to add a new list item (which comes from an API) when a button is pressed, but I'm not sure how to do it. Can anyone provide some guidance? Here's the code: <ul> <li *ngFor="let joke of jokes">{{joke.value}}</li> ...

Axios displays a status code of 0 instead of the expected 403

Trying to monitor the responses of requests using axios response interceptors has been quite a challenge for me. In one specific request that necessitates authorization, everything goes smoothly when the token is valid, and data is returned without any is ...

What is the best way to link a variable to a specific property within a

I am facing an issue with adding data from the server to a JSON property and displaying it. I know that JSON only accepts primitive types, so how can I dynamically add data to a JSON property? For instance, in the code snippet below, I am trying to assign ...

How to create a custom hover effect for IconButtons in Material-UI

Customizing Hover Effects on IconButton I am currently using an IconButton component from Material-UI and have noticed a subtle grey border that appears when hovering over the icon. I am looking for a way to disable this hover effect, as I cannot seem to ...

What method does AngularJS use to distinguish between these two properties?

I grasp the concept that ng-model generates a property that corresponds to the {{name}}. How does AngularJS distinguish between the {{name}} derived from the ng-model and the {{name}} originating from the ng-repeat/ng-init? <section class="section"> ...

"Maintaining Consistency: Ensuring The First Row is Repeated on Every

When trying to save a PDF using jspdf, I encountered an issue with tables in my HTML. The tables do not have headers, but JsPDF is automatically repeating the first row of the table on every page, causing overlap. I don't want headers on every new pag ...

I am experiencing issues with the rendering of my q-btn elements in Quasar and they are

I recently started using Quasar and encountered an issue with my q-btn component buttons displaying white backgrounds at random, despite having added a background-color in the external stylesheets. Here are some examples of this perplexing problem: https ...

Personalized jQuery Slider, Go back to initial slide

Working on enhancing my jQuery skills by constructing a basic slider with 3 slides. The slider wrapper, with a fixed width of 1400px and a height of 350px serves as the outer container. Within this wrapper lies an unordered list where its items are floate ...

Understanding the sequence of operations in Javascript using setTimeout()

If I have the following code: function testA { setTimeout('testB()', 1000); doLong(); } function testB { doSomething(); } function doLong() { //takes a few seconds to do something } When I run testA(), what happens after 1000 mill ...

Error: The property 'scrollIntoView' cannot be read because it is null

class MessageApp extends Component { constructor(props) { super(props) this.state = { text: "", messages: [] } } componentDidMount() { const config = { apiKey: "<api-key>", authDomain: "<projec ...

Exploring the use of MediaSource for seamless audio playback

Currently working on integrating an audio player into my Angular web application by following a tutorial from Google Developers and seeking guidance from a thread on Can't seek video when playing from MediaSource. The unique aspect of my implementati ...

Mongoose fails to save due to an error stating "undefined id"

Having some trouble with the Mongoose save function... In my user model file: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const User = mongoose.model('User', { name: Schema.Types.Mixed, gender: String, ...

Another option instead of using $index for displaying serial numbers in ng-repeat

Looking to display a serial number for each table data entry being generated through the use of ng-repeat. The current code I have is as follows: <tr ng-repeat="usageRecord in applicationUsageDataForReport"> <td style="text-align: center">&l ...

Issue with Fullcalendar's events.php causing JSON object retrieval failure

I'm attempting to send a JSON object as a response to my fullcalendar ajax request, but instead of returning the desired result, it only returns an array. Although I am relatively new to JSON and PHP, I have conducted extensive research and have yet t ...

A guide to increasing a loop counter in Vue

Having trouble looping through a specific group of objects in a multi-object array? Take a look at the code below: <template> <div> <h1>My Test App</h1> <button v-on:click="getHockeyData">Get Team Data< ...