Back to articles
Confused by Mouse Coordinates in Three.js? Here’s the 2-Minute Explanation

Confused by Mouse Coordinates in Three.js? Here’s the 2-Minute Explanation

via Dev.to JavaScriptPeter Riding

Ever clicked a 3D object in Three.js and the raycaster hits somewhere completely wrong? You're not alone. The fix is just a few lines of code — but the why is what confuses most people. Here’s the simple explanation. The raycaster doesn't use pixels It works in the camera’s coordinate system using Normalized Device Coordinates (NDC) — values from -1 to +1 . X: -1 = left, +1 = right Y: +1 = top, -1 = bottom So instead of pixels, it uses a normalized coordinate system based on the screen (you can think of it like percentages). The conversion (this is the important part) const mouse = new THREE . Vector2 (); mouse . x = ( event . clientX / window . innerWidth ) * 2 - 1 ; mouse . y = - ( event . clientY / window . innerHeight ) * 2 + 1 ; raycaster . setFromCamera ( mouse , camera ); What’s happening here: event.clientX / width → gives a value from 0 → 1 across the screen We remap that to -1 → +1 Same for Y, but flipped because browser coordinates start at the top In other words, you're con

Continue reading on Dev.to JavaScript

Opens in a new tab

Read Full Article
2 views

Related Articles