Interacting with Elements in three.js when the canvas is not in full screen mode version 74

Appreciate you taking the time to help me with my question.

I'm having trouble finding a good example of how to use raycaster in three JS version r74.

There have been many changes between versions r55 and r76, and forums seem to focus on examples from minor versions of Three.js.

Could someone provide an example for us?

By the way, I am using Angular and Bootstrap.

This is what I have tried so far:

My View

<div class="col-md-11">
  <div class="container">
    <div class="panel panel-default">
      <div class="panel-heading">
        <h3 class="panel-title">Title</h3>
      </div>
      <div class="panel-body" style="padding: 0px">
        <div class="canvas-zonas" ng-click="zonas.click($event)">
        </div>
      </div>
    </div>
  </div>
</div>

My Css (using stylus)

.canvas-zonas
  height 67vh

My Controller

var mouse = new THREE.Vector3();
var raycaster = new THREE.Raycaster();
var canvas = document.querySelector(".canvas-zonas");

function clickObject(event) {
      event.preventDefault();
      mouse.x= ((event.clientX - canvas.offsetLeft)/canvas.clientWidth) * 2 - 1;
      mouse.y=-((event.clientY - canvas.offsetTop)/canvas.clientHeight) * 2 + 1;
      mouse.z = 0.5;
      raycaster.setFromCamera(mouse, camera);
      var intersects = vm.raycaster.intersectObjects(scene.children);
      console.info(intersects);
    }

When I click on my canvas and print the Intersects variable, sometimes I get an empty array even if I click on the object, and sometimes I get [object] even if I click outside the object.

I'd like to share some details about my camera configuration:

My Camera

var camera = new THREE.PerspectiveCamera(30, canvas.clientWidth / canvas.clientHeight, 0.10, 1000)
camera.position.y = 20;
camera.position.z = 50;
camera.lookAt(scene.position);
camera.updateProjectionMatrix();

That's how my camera is set up, and just a reminder that I am using WEBGL as the renderer.

var renderer = new THREE.WebGLRenderer({antialias: true});

Also, don't forget that there is a resize event happening:

function listenResize() {
  window.bind('resize', function () {
    canvas = document.querySelector(".canvas-zonas");
    renderer.setSize(canvas.clientWidth, canvas.clientHeight);
    camera.aspect = (canvas.clientWidth / canvas.clientHeight);
    camera.updateProjectionMatrix();
  });
}

Lastly, below are two images showing what's happening:

Image 1

https://i.sstatic.net/O8Xko.png

Image 2 https://i.sstatic.net/noPcy.png

Thank you very much, and apologies for my previous post. I have made updates!

Answer №1

I encountered the same issue and after scouring the internet for two days, I stumbled upon a solution that worked well:

let canvasBounds = this.renderer.context.canvas.getBoundingClientRect();
this.mouse.x = ( ( event.clientX - canvasBounds.left ) / ( canvasBounds.right - canvasBounds.left ) ) * 2 - 1;
this.mouse.y = - ( ( event.clientY - canvasBounds.top ) / ( canvasBounds.bottom - canvasBounds.top) ) * 2 + 1;

Reference: THREE.js Ray Intersect fails by adding div

Acknowledgements:

  • Y coordinate - Solution provided by "Kris Roofe".
  • X coordinate - Appreciation to "beepscore" for their comment on Kris Roofe's answer.

May this solution be of assistance to others facing similar challenges.

Answer №2

Over the years, it seems that there may have been some changes ... however, I have found success with this method of mapping mouse coordinates to (-1, 1) despite any canvas resizing:

mouseVector.x = 2 * (e.x / canvas.offsetWidth) - 1;
mouseVector.y = 1 - 2 * ((e.y - canvas.offsetTop) / canvas.offsetHeight);
mouseVector.z = 0.5;

Keep in mind that offsetHeight and height are not equivalent! The same goes for width.

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

Ways to obtain every image placed onto an element

Using the img tag within div.image-block sets a background. Images can be added to .block3 through drag and drop. Is there a way to create a container that includes all elements from .image-block? <style> .image-block { position: relat ...

Numerous Ajax calls made to Flask-Python endpoint - Yet, only one was successful

i'm attempting to iterate through several forms with input file type and employ Ajax to send them to Flask This is how the javascript looks like :- I have a list of forms stored in the variable var upFC = document.getElementsByClassName('upload ...

Angular failing to update $scope variable within controller

I need to implement a directive that allows file uploading directly to the browser angular.module('angularPrototypeApp') .directive('upload', ['$parse', function ($parse) { return { restrict: 'A', scope: fal ...

What is the best way to incorporate Vue.js component dependencies into a multi-page application (MPA

When working with a multiple page app, incorporating a component inside another component can be challenging, especially without using a build system. $ npm install sagalbot/vue-select <template> <div id="myApp"> <v-select :value.sy ...

Modifying shapes and figures in three-dimensional Javascript

I am currently struggling to transform a cube into a sphere in Three.js either after a specific time interval or upon an event click. I have attempted changing the geometry property from BoxGeometry to SphereGeometry with no success. Despite trying some po ...

Establishing Jest setup for React (Native) to test components in Context

Utilizing the React Context API enables me to consolidate the logic for the application state in a single location, eliminating the need for redux. Here is how the current setup looks: // This code snippet demonstrates the use of Context API in React 16.3 ...

How can I assign a prop to a component within the root layout in Next.js version 13, especially when the root layout is required to be a server-side component at all times?

I need assistance with a project I'm working on. My goal is to create a SongPlayer component in Next.js version 13 that plays music and is positioned at the bottom of the window, similar to Spotify's player. However, my SongPlayer component requi ...

Focusing in on the mouse location to magnify a THREE.js element

I am currently working on a project using THREE.js and I have encountered an issue with zooming the object. The zoom functionality is centered around the render position when using trackball controls, but I need it to be based on the cursor's position ...

Utilize the objects array property to filter an array of objects

Struggling to wrap my head around this, not sure if it's feasible in this manner but I just can't seem to grasp it. I have an array of objects where each object contains some values and another array of objects. Essentially, I need to filter the ...

What is the best way to make ASP dropdownlist as read-only using CSS or JavaScript?

I'm having trouble setting a dropdown list to read-only. I've tried setting enabled = false, but then the font color appears blurry and distorted. The same technique works fine for textboxes using textbox.readonly = false. Is there a way to achie ...

What is the purpose of using async/await in Node.js when it is inherently asynchronous, and in JavaScript as well, vice versa?

Apologies for my lack of experience in Javascript and NodeJS. I'm a total beginner, so please excuse my silly questions. I've been trying to wrap my head around the concept but haven't found a clear explanation. Here's what's conf ...

Layers of objects obscured by other objects using an OrthographicCamera

I'm having an issue where a box is hidden behind a polygon when using an OrthographicCamera, but works fine with a PerspectiveCamera. If you want to see the problem in action, check out my codesandbox here: https://codesandbox.io/s/gifted-bush-wbnlvy ...

Having trouble interacting with the "Continue" button on PayPal while using Selenium

Recently, I have encountered an issue with automating payments via PayPal Sandbox. Everything used to work smoothly, but now I am unable to click the final Continue button no matter what method I try. I have attempted regular clicks, using the Actions cl ...

Reactjs Invariant Violation caused by the npm package (react-loader)

I'm currently attempting to integrate react-loader into my react component. This is the code snippet I'm using: /** @jsx React.DOM */ var Loader = require('react-loader'); var DisplayController = React.createClass({ // etc ...

encountering a glitch during the electron.js build process with nextjs

When attempting to build Electron.js with Next.js, I keep encountering this persistent error. I have updated my packages and reinstalled node modules multiple times, but I am still unable to resolve it. C:\Users\Himanshu\Desktop\claros& ...

Drop down list not showing array values

I am attempting to populate a dropdown list with elements from an array using the Document Object Model (DOM) within a for loop. However, I keep encountering an error stating that the dropdown list is null. Here is the JavaScript code I am using: var st ...

Converting JavaScript to PHP and encountering problems with POST encoding

Trying to send a string from JavaScript on the client-side to a PHP script on the back-end. The string has special quotes like ’ and “. When checking the console in Chrome, the POST headers show these special characters as they are. On the PHP side, I ...

Having trouble with HtmlInput.focus() functionality in react.js?

I am trying to develop a React app for measuring typing speed. However, I have encountered an issue with my code. Here is a snippet of the code I'm working on: { txt && txt.map((c, i) => ( <Character key={i} ...

Problem with using Twitter Bootstrap in IE11 when Browser Profile Enterprise is enabled

I am facing an issue with a Bootstrap 3 web page. Some machines have IE configured to load intranet pages in Enterprise profile mode, while others have the default Desktop profile set in IE11. This configuration has caused the layout to break completely. ...

IDs in Meteor Collections: Choose between Random.id() or Meteor.Collection.ObjectID()

When I add files to my Meteor collections, they are given a unique _id in the form of Random.id: Random.id(); // "wjQyQ6sGjzvNMDLiJ" If I add files directly from MongoDB to those same collections, they receive an _id represented as Meteor.Collection.Obje ...