It seems like the issue lies in how the mouse coordinates are being interpreted relative to the browser viewport, rather than the canvas where the THREE.js scene is displayed. The coordinate (0, 0) corresponds to the top left corner of the browser viewports, while ideally it should align with the top left corner of the canvas. This discrepancy may be due to the presence of a navbar, which requires adjustments to accurately capture the mouse position on the screen.
To calculate the offset between the canvas and the viewport edge, you can utilize the canvas.getBoundingClientRect() method. This function provides information about the canvas size and its position within the viewport.
To access the canvas rendered by THREE.js renderer, you can use renderer.domElement. Alternatively, you can assign a custom canvas to the renderer during initialization using a designated canvas element.
var canvas = document.getElementById("canvasID");
renderer = new THREE.WebGLRenderer({ canvas: canvas });
Subsequently, you can employ the following function to determine the mouse coordinates relative to the canvas:
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
This function enables retrieval of accurate mouse position data with respect to the canvas.
If necessary, please consider sharing the code snippet used for obtaining mouse positions to facilitate better assistance. Remember to include relevant code when seeking help on platforms like stack overflow.
EDIT:
For optimal results, ensure that the mouse coordinates are captured immediately before usage. Modify the capturing code as follows:
var vector = new THREE.Vector3();
var mousePos = getMousePos(canvas, event);
vector.set( ( mousePos.x / window.innerWidth ) * 2 - 1,
- ( mousePos.y / window.innerHeight ) * 2 + 1, 0.5 );
vector.unproject( camera );
If passing the canvas as an argument poses challenges, consider making the renderer globally accessible. Update the function call accordingly:
var mousePos = getMousePos(renderer.domElement, event);
Following successful testing, explore methods to obtain canvas elements without relying on global variables, enhancing code structure and optimization.
Proceed by utilizing DOM techniques to retrieve the canvas based on identifiers or alternative approaches. Best wishes for resolving this issue!