In my Three.js project, I am using an OrthographicCamera and OrthographicTrackBallControls for zooming and panning. I am attempting to implement a functionality to zoom to the cursor position, but so far, I have been unsuccessful. To start, here is how I am retrieving the mouse position:
var mX = ((event.clientX - offset.left) / renderer.domElement.clientWidth) * 2 - 1;
var mY = -((event.clientY - offset.top) / renderer.domElement.clientHeight) * 2 + 1;
var vector = new THREE.Vector3(mX, mY, 0.5);
vector.unproject(camera);
vector.sub(camera.position);
After researching on StackOverflow, I found that there is a lot of information on achieving this with a PerspectiveCamera, but those methods do not work with the OrthographicCamera I am using. There is an example here that demonstrates what I am trying to achieve, but the code responsible for it is hidden, although it appears that the camera position is being adjusted.
Another similar question on StackOverflow suggests modifying camera.left, camera.right, camera.top, and camera.bottom, but I have not had success with this approach. While it seems like a viable option, I am unsure about the calculations required to obtain the correct values for these properties.
As I see it, I have two potential approaches:
- Adjust the camera's left/right/top/bottom to obtain the correct view rectangle.
- Modify the camera's position.
However, I do not know how to determine the values needed for either method, let alone which approach is preferable.
UPDATE 11/16/2018:
I have updated my function based on this example:
zoomDirection = new THREE.Vector3();
function mousewheel(event) {
event.preventDefault();
var amount = event.deltaY / 100;
var zoom = camera.zoom - amount;
var offset = el.offset();
;
var mX = amount > 0 ? 0 : ((event.clientX - offset.left) / renderer.domElement.clientWidth) * 2 - 1;
var mY = amount > 0 ? 0 : -((event.clientY - offset.top) / renderer.domElement.clientHeight) * 2 + 1;
zoomDirection.set(mX, mY, 0.001)
.unproject(camera)
.sub(camera.position)
.multiplyScalar(amount / zoom);
camera.position.subVectors(camera.position, zoomDirection);
orthographictrackBallControls.target.subVectors(orthographictrackBallControls.target, webGl.zoomDirection);
camera.zoom = zoom;
camera.updateProjectionMatrix();
}
Initially, this seems to work as intended: the camera zooms to the mouse point. However, after some zooming, the camera begins to "jump" erratically, with the mesh no longer appearing on the screen.
An indicator that might help is that I have an axis helper on the screen that changes orientation when the issue arises. When the scene loads, the X-axis helper points to the left, but when the camera starts jumping and the mesh disappears, the X-axis helper rotates to point right.
Additionally, if I first zoom out, I can then zoom in further before the mesh vanishes. I am uncertain of the significance of these observations, but any assistance would be greatly appreciated.