When your render is contained within a window or block with an absolute position, using window.innerWidth
may result in incorrect coordinates. Additionally, attaching the mouse move event to the entire window can be inefficient.
A more effective approach would be:
const renderBlock = document.querySelector('#threeJSRenderWrapper');
let renderWidth = renderBlock.offsetWidth;
let renderHeight = renderBlock.offsetHeight;
const camera = new THREE.PerspectiveCamera(60, renderWidth / renderHeight, 0.01, 100000);
// This section can be placed inside the window resize function
camera.aspect = renderWidth / renderHeight;
camera.updateProjectionMatrix();
renderer.setSize( renderWidth, renderHeight );
const pointer = new THREE.Vector2();
renderBlock.addEventListener( 'pointermove', onPointerMove );
function onPointerMove( event ) {
// Calculate pointer position in normalized device coordinates
// (-1 to +1) for both components
pointer.x = ( event.layerX / renderWidth ) * 2 - 1;
pointer.y = - ( event.layerY / renderHeight) * 2 + 1;
}
// Include remaining code for mouse intersection or other functionality
Using event.layerX
and event.layerY
will provide accurate coordinates relative to the block to which the mousemove
event is attached.