jonobr1 / two.js

A renderer agnostic two-dimensional drawing api for the web.
https://two.js.org
MIT License
8.3k stars 455 forks source link

Relative Mouse Position #652

Closed abdobrianZverse closed 2 years ago

abdobrianZverse commented 2 years ago

Describe your question

One of our features requires that we click on a two.js surface that has a sprite on it. When this occurs, we show a div at the position of the click overlaying the sprite.

We've been having issues with two js on resize. EDIT: We're mostly concerned about resize of the window on refresh / going back to the page (x,y) coordinates are stored remotely and fetched.

When resize occurs, the x,y coordinates we have mapped for divs outside of two js needs to be remapped. We have tried translating the mouse position based on percentage of the screen size but that does not seem to correlate 100% to the sprite we are overlaying in two.js.

We've also tried the approach of using the surfaceToClient to remap as well and that doesn't seem to correlate either.

We are in fullscreen mode so there is no top or left offset for the bounds on resize.

My understanding is that all ZUI is trying to do is a screen space to world space transformation / visa versa. Am I missing something here?

How would we resolve this issue?

abdobrianZverse commented 2 years ago

This is actually more of a react issue than a twojs issue. Just needed to orient how i though of relative space within twojs and how it integrates with screen space in a react environ.

jonobr1 commented 2 years ago

Hard to know exactly the problem without an example, but I find this to be very reliable:

window.addEventListener('pointermove', mousemove, false);
function mousemove(e) {
  const rect = two.renderer.domElement.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;
  // Do whatever Two.js calculations you need to do
}

But this assumes you aren't doing any rotation or scaling on the parent DOM element.