Selecting Objects with a Mouse in Three.js

Thanks to the wonderful support from the stackoverflow community, I was able to successfully implement a basic object picking example.

You can view the functional code here.

However, it's important to note that this example specifically works when the canvas perfectly fits the window size.

The issue arises when the canvas is smaller than the window and has left and top offsets, leading to inaccuracies in object picking.

How do we correct this offset problem? What modifications need to be made to ensure proper object picking functionality?

I've attempted different solutions like adjusting

renderer.setSize(threejsCanvas.clientWidth, threejsCanvas.clientHeight);
, but none have been successful so far.

Answer №1

The issue here arises from the utilization of window.innerWidth and .innerHeight to determine the position of your raycaster:

  mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
  mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

If the width of your canvas doesn't match window.innerWidth, make sure to use the specified size you've provided. Additionally, it's advisable not to attach the "click" event directly to document, but rather consider adding it to renderer.domElement so that it only activates when clicking within the canvas.

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

Attempting to configure a discord bot. Can anyone help me identify the issue?

I've been working on setting up a discord bot using Discord.js. I have all the necessary tools installed - Node.js, Discord.js, and Visual Studio Code. I've even created an application and obtained a token for my bot. However, I'm running in ...

How can I pass a value from JavaScript back to the .blade file in Laravel using DataTables?

I have some rows that are being displayed: https://i.sstatic.net/Y10X7.png The DataTable plugin within app.js is responsible for outputting each row. My goal is to target a specific value, ${row.category_id} let TABLE = $('#categoryList').Data ...

Exploring the capabilities of AngularJS directives through ng-html2js testing

Many questions have been raised about the ng-html2js plugin, but unfortunately, none of the answers provided were able to solve my specific issue. I meticulously followed the official installation guide and also referenced the example available at https:/ ...

What is the typical approach of JavaScript frameworks towards the 304 not-modified response?

Wondering about the inner workings of Jquery and web development in general. When a JavaScript file is requested and the server sends a 304 not-modified response, how does a framework handle it: Does it load the JS file from cache and run it? Or does it ...

What is the best way to ensure that the operations are not completed until they finish their work using RX

Is there a way to make RXJS wait until it finishes its work? Here is the function I am using: getLastOrderBeta() { return this.db.list(`Ring/${localStorage.getItem('localstorage')}`, { query: { equalTo: fa ...

Getting Your Redux Form Ready for Submission

I recently transformed my Redux form into a wizard with multiple subcomponents following the structure outlined here: However, I'm encountering difficulties when trying to integrate the form with my actions to submit the form data. Unlike the example ...

Issues with sending an AJAX POST request to a PHP script

Hello, I am trying to send a variable from an AJAX JavaScript file to a PHP file. Here is what I have done so far: var request = createRequest(); var deletenode = node.id; window.alert("nodeid=" + deletenode); var vars = "deletenode ...

Troubleshooting Next.js and NextAuth.js Authentication Redirect Issue

I am experiencing a problem with authentication in my Next.js application using NextAuth.js. The issue specifically pertains to the redirection after successful login. Here is an overview of my setup: NextAuth.js Configuration (app/api/auth/[...nextauth.js ...

Performing an API GET request in a header.ejs file using Node.js

Looking to fetch data from an endpoint for a header.ejs file that will be displayed on all routed files ("/", "/news" "/dogs"). Below is my app.js code: // GET API REQUEST var url = 'https://url.tld/api/'; request(url, function (error, response, ...

Deactivate Date Field for Editing Orders in WooCommerce

Is there a way to deactivate the Date Created textbox on the Edit Orders page of Woocommerce? I attempted to use pointer-events: none; but unfortunately, it did not have any effect. I am seeking a method to disable the Date Created field. https://i.sstat ...

What is the best method for opening .xls files using ExcelJS?

I am facing an issue with accessing a .xls file using the ExcelJS library. Interestingly, there are no issues when it comes to reading .xlsx files. Previously, I relied solely on the xlsx js library and never encountered any problems while accessing .xls f ...

Utilize Meteor and Mongo to access a nested array object in a template with spacebars

I am trying to populate the content of a textarea by extracting data from a nested array. In my helper function, I have specified the document id and the element id. The goal is to extract the content of the text field from the findOne result and display i ...

Is it possible to execute user-defined functions dynamically in a Node.js application without having to restart the server

I am exploring the potential for allowing users to insert their own code into a Node application that is running an express server. Here's the scenario: A user clicks 'save' on a form and wants to perform custom business validations. This ...

Error in AngularJs: [$injector:modulerr] Unable to create schemaForm module instance

Trying to integrate angular-schema-form into AngularJs Seed has been a challenge. Following the steps outlined in the angular-schema-form repository: view1.js 'use strict'; angular.module('myApp.view1', ['ngRoute', 'sc ...

Utilizing a JavaScript variable in Jquery for managing an mp3 playlist

I am working on implementing an album feature for the jPlayer that is already in use. Here is the current static code: $(document).ready(function(){ new jPlayerPlaylist({ jPlayer: "#jquery_jplayer_1", cssSele ...

Combining arrays of objects in VueJS

I am working with 2 components: parent component (using vue-bootstrap modal with a vue-bootstrap table) child component (utilizing vue-bootstrap modal with a form) Issue: When I submit the form in the child component, it successfully adds the object to ...

Double quotes in JSON are not being escaped properly

When I try to evaluate some json on a screen, I keep encountering errors with the message 'unexpected identifier'... The problematic data that seems to be causing this issue is: "itemDescription":"STANDARD \"B\" RED BOX", To address ...

Navigating the art of employing different fonts for a website

I am looking to incorporate the trainway font into my website, but I'm concerned that the user may not have it installed on their device. Is there a way to showcase text in a specific font without requiring the user to download and install it? Thank ...

Adding jQuery content to a div that is being created dynamically

Currently implementing a save/load feature using JSON for a diagram that utilizes jsPlumb. While the save functionality is working perfectly, the load functionality is encountering difficulties in replicating the full initial saved state. The issue arises ...

Integrating information from an API into the Document Object Model

const url = `https://catfact.ninja/fact?max_length=140`; const getFact = () => { return fetch('https://catfact.ninja/fact?max_length=140') .then(res => res.json()) } const createFactDiv = (fact) => { const factContainer = documen ...