daybrush / infinite-viewer

Infinite Viewer is Document Viewer Component with infinite scrolling.
https://daybrush.com/infinite-viewer/
MIT License
283 stars 30 forks source link

Multiplayer cursor position inside canvas #70

Open alquist42 opened 6 months ago

alquist42 commented 6 months ago

Hello again :)

I'm trying to play with multiplayer presence technology and to show the other participant cursor position inside invinite viewer.

infinite-viewer-cursors

But as you can see the cursors have window position and not adjusted to scrolled area and not to zoom of the invinite viewer. For example, when one cursor on "div 5" second on "div 4" I've tried couple of things of adjusting relativly to container, but no luck yet...

Can you please advise of how to adjust the coordinate to reflect the real world inside the canvas?


Playground: codesandbox (hot reload breaks sometime, so need to refresh manualy, you can add second preview tab)


A huge thanks anyway!

kevinvalk commented 6 months ago

Took me way to long as well, but this should give you a stable mouse position that is absolute regardless zoom or scroll.

viewport.addEventListener('mousemove', (e) => {
  const rect = viewport.getBoundingClientRect();
  mouse.x = (e.clientX - rect.left) / infiniteViewer.zoomX;
  mouse.y = (e.clientY - rect.top) / infiniteViewer.zoomY;
});

NOTE: This is not it either as it "stops" tracking when you are outside the viewport element...