I am facing an issue where reducing the size of the renderer is causing my click events to be offset. What steps can I

At the moment, my rendered model (which is grey in color) stretches across the entire width of the html page with the mesh centered within that width. I want to reduce this width but when I do so, the click event on the model seems to be misaligned. Three.js still believes that my mesh is at the center of the width even though it has actually shifted to the left due to the decreased width.

Here's an example of the code:

Currently, I have something like this where the first step involves creating a renderer that places the rendered object which takes up the full width of the screen and centers the rendered object within that width. This particular code example works perfectly:

var WIDTH = window.innerWidth;
  HEIGHT = window.innerHeight/2;

  // Create a renderer and add it to the DOM.
  renderer = new THREE.WebGLRenderer({antialias:true});
  renderer.setSize(WIDTH, HEIGHT);

I then insert the rendered image into a div on my html page.

container = document.getElementById( 'canvas' );
  document.body.appendChild( container );
  container.appendChild( renderer.domElement );

Next, I create a mesh and add it to an array called targetList

mesh = new THREE.Mesh(geometry, material);
    mesh.position = new THREE.Vector3(0, -3, 0) ;

    projector = new THREE.Projector();  
    document.addEventListener( 'mousedown', onDocumentMouseDown, false );

    scene.add(mesh);
    targetList.push(mesh);

Whenever someone clicks on the rendered image, the following function is triggered:

function onDocumentMouseDown( event ) 
{
   console.log("Click.");
   // update the mouse variable
   mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
   mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;

   // find intersections
   var vector = new THREE.Vector3( mouse.x, mouse.y, 1 );
   projector.unprojectVector( vector, camera );
   var ray = new THREE.Raycaster( camera.position, vector.sub( camera.position ).normalize() );

   // create an array containing all objects in the scene with which the ray  intersects
  var intersects = ray.intersectObjects( targetList );

  // if there is one (or more) intersections
  if ( intersects.length > 0 )
  {
      console.log("Hit @ " + toString( intersects[0].point ) );
  }

} 

Everything works fine and accurate, giving me precise outputs when clicking inside the rendered model.

Hit @ [ -0.12506098558617107, 2.650102060480923, 1.2154427674550532 ]

The Problem Begins

However, the issue arises when I decrease the width and modify the initial statement:

var WIDTH = window.innerWidth;

to var WIDTH = window.innerWidth/2;

After making this adjustment, when I click on the image I only get a "click" output and for some reason, Three.js fails to recognize that I clicked on the model. If I click in the center (previous position of the model), Three.js thinks that the click occurred inside the model. My question is, why does reducing the width cause my model to move left on the screen affect the coordinates? Why does Three.js still believe that my model is centered?

Answer №1

Modifying the dimensions of the render does not alter the size of the window. Therefore, when you perform an unprojection of the mouse, it is crucial to take this into account. The operation to "update the mouse variable" can be achieved by using the following code snippet:

mouse.x = ( event.clientX / (window.innerWidth/2) ) * 2 - 1;
 mouse.y = - ( event.clientY / (window.innerHeight/2) ) * 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

What could be causing my Vue.js sorting array script to malfunction?

I'm encountering an issue with sorting the table by Date. The sort function used to determine the type of sorting no longer works, and I'm unsure why. html: <th @click = "sort('data_produktu')" class="date">Da ...

What is the best way to incorporate images from an external module into my React project?

Is there a way to include images from an external module (npm install external-module) in my project's public assets? The images are located in the directory path myProject/node_modules/external-module/dist/img. ...

Learn how to pass an id from the query parameters to the getInitialProps function in Next.js

Looking to create a basic website that displays content from a database? Utilizing the getInitialProps function from Next.js documentation can help with server-side rendering: https://nextjs.org/docs/api-reference/data-fetching/getInitialProps#getinitialpr ...

Ways to implement a scrollable v-list component using Vuetify

I have set up a v-list using flex layout, where the v-list expands to fill the remaining space horizontally in a column. However, if the list contains many elements with a total height that exceeds the column's height, the list ends up sticking out of ...

Exploring the potential of Oracle Openscript in combination with Javascript using AngularJS,

I have encountered an issue while using Openscript on a form page with a clickable "save" button implemented as a div. Manually clicking the button triggers a javascript event that saves any changes made on the page. However, when I run the script, the but ...

Implementing a click function that toggles between adding and removing a class, keeping track of the number of clicks, and utilizing localStorage to prevent repeated clicking in the

Hi there! I'm currently working on a simple widget that features a clickable icon and a counter next to it. When the icon is clicked, it should toggle between an empty heart and a filled heart using addClass/removeClass. Additionally, each click incr ...

Exploring complex nested data structures

I've been tackling a component that manages labels and their child labels. The data structure and rendering process are sorted out, as shown in this example. However, I'm at a roadblock when it comes to manipulating the data effectively. Specif ...

Utilizing hooks in node.js functions

Is there a way to apply before and after hooks on a function? I need these hooks to trigger whenever the function is called. While Express.js middleware concept works for routes, I require similar hooks for functions on the server side. function main(){ ...

How can it be that "Function" actually functions as a function?

In JavaScript, there exists a function called "Function". When you create an instance of this function, it returns another function: var myfunc = new Function('arg1','arg2','return arg1+arg2'); In the above example, the vari ...

Looking for assistance with retrieving all files from a directory based on their file extensions in JavaScript

Looking for a way to gather all the '.txt' files from a folder that also contains a 'backup' folder, and moving them into the 'backup' folder using Node.js. If you have any suggestions, please share. Thanks! Best regards, M ...

The content momentarily flashes on the page during loading even though it is not visible, and unfortunately, the ng-cloak directive does not seem to function properly in Firefox

<div ng-show="IsExists" ng-cloak> <span>The value is present</span> </div> After that, I included the following lines in my app.css file However, the initial flickering of the ng-show block persists [ng\:cloak], [ng-cloak], ...

Can you transform text with accents into plain ASCII characters?

I am seeking a solution in Javascript to convert accented letters and various encodings into plain English ASCII characters. The goal is to achieve the following transformations: éclair ~becomes~ eclair bär ~becomes~ bar привет ~becomes~ privet ...

Tips for eliminating whitespace from an input field and then updating the field with the trimmed value

Currently, I am working on email validation where users might input empty spaces in the email field. To address this issue, I have implemented a logic to trim the input value using $trim and then re-assign it to the input field. Although everything seems ...

Creating a "briefing" iframe at the top of a webpage

I'm looking for a way to allow users to embed my iframe at a specific size, like 100x100, and then have it resize dynamically to fit the page size when they click on it. I want this functionality to work regardless of how the HTML embedding the iframe ...

Attempting to showcase JSON response within an HTML page using JavaScript

Can anyone help me troubleshoot my code for displaying JSON data on a web page? Here's what I have so far: <button type="submit" onclick="javascript:send()">call</button> <div id="div"></div> <script type="text/javascript ...

How can you create a smooth transition between two images in React Native?

I'm looking to create a cool effect with two images that gradually fade into each other. My initial approach involved layering one image over the other and adjusting its opacity using timing or animation functions, but I've been struggling to ge ...

I possess a function that can retrieve the key of an Object, but now I am faced with the task of accessing the actual Object using this value in JavaScript

This is my first time seeking advice on a technical issue. I'm currently working with the following function: export function sendRequest<T>(req: RawRequest, options) { const start = Date.now(); const reqOptions: CoreOptions = { ...

Angular 1.4.8 Issue: [$injector:modulerr]

I can't seem to identify the main cause of this error. I consistently see a green underline below the word angular in my javascript file. I'm not sure why. (Using Visual Studio Code) HTML <html ng-app="myapp"> <head> ...

Having trouble importing SVG as a React component in Next.js

I initially developed a project using create-react-app with Typescript, but later I was tasked with integrating next.js into it. Unfortunately, this caused some SVGs throughout the application to break. To resolve this issue, I implemented the following pa ...

Is JQueries Live functionality compatible with IE8?

Incorporating the JQuery fancy box, I have implemented a pop-up form with select fields that dynamically update a span element upon selection change. Although it works well thanks to fellow Stack Overflow users' help, it unfortunately does not functio ...