Converting World coordinates to Screen coordinates in Three.js using Projection

Viewed 43876

There are several excellent stack questions (1, 2) about unprojecting in Three.js, that is how to convert (x,y) mouse coordinates in the browser to the (x,y,z) coordinates in Three.js canvas space. Mostly they follow this pattern:

    var elem = renderer.domElement, 
        boundingRect = elem.getBoundingClientRect(),
        x = (event.clientX - boundingRect.left) * (elem.width / boundingRect.width),
        y = (event.clientY - boundingRect.top) * (elem.height / boundingRect.height);

    var vector = new THREE.Vector3( 
        ( x / WIDTH ) * 2 - 1, 
        - ( y / HEIGHT ) * 2 + 1, 
        0.5 
    );

    projector.unprojectVector( vector, camera );
    var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );
    var intersects = ray.intersectObjects( scene.children );

I have been attempting to do the reverse - instead of going from "screen to world" space, to go from "world to screen" space. If I know the position of the object in Three.js, how do I determine its position on the screen?

There does not seem to be any published solution to this problem. Another question about this just showed up on Stack, but the author claims to have solved the problem with a function that is not working for me. Their solution does not use a projected Ray, and I am pretty sure that since 2D to 3D uses unprojectVector(), that the 3D to 2D solution will require projectVector().

There is also this issue opened on Github.

Any help is appreciated.

4 Answers

None of these answers worked for me but they were very close, so I investigated a little bit more and combining some code from those answers plus this article I was able to make it work with the following snippet

const vector = new THREE.Vector3();
const canvas = renderer.domElement; // `renderer` is a THREE.WebGLRenderer

obj.updateMatrixWorld();  // `obj´ is a THREE.Object3D
vector.setFromMatrixPosition(obj.matrixWorld);

vector.project(camera); // `camera` is a THREE.PerspectiveCamera

const x = Math.round((0.5 + vector.x / 2) * (canvas.width / window.devicePixelRatio));
const y = Math.round((0.5 - vector.y / 2) * (canvas.height / window.devicePixelRatio));
Related