TrackballControls - zoom by mouse cursor gone wrong

I’m trying to make the graph zoom according the mouse cursor, by override the mouse wheel behavior of trackballControls.js. What happens:

  1. It works partly and the graph zooms but not directly to the cursor.
  2. Right side zooms faster the the left, it seems like camera vector is not going straight but diagonal.

What can be the reasons for that? I copied only the wheel code part codepen and it works without those problems…

codepen which shows the problem:

A recording which shows the problem is attached!

thanks!

2020-10-01 22-57-58.mkv (1.1 MB)

After research I see the problem stems from the canvas starting not in (0, 0) but in some other (x, y) offset points of the screen. Thus, mouse position is not being translated properly.
Solution is to subtract the canvas top and left offset from the top of the page.

   const rect = controls.domElement.getBoundingClientRect();
   const x = ((event.clientX - rect.left) / clientWidth ) * 2 - 1;
   const y = -((event.clientY - rect.top) / clientHeight ) * 2 + 1;