35
votes

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.

3
Thanks so much for the "screen-to-world" translation pattern. It was a pain for many hours..lephleg

3 Answers

37
votes

Try with this:

var width = 640, height = 480;
var widthHalf = width / 2, heightHalf = height / 2;

var vector = new THREE.Vector3();
var projector = new THREE.Projector();
projector.projectVector( vector.setFromMatrixPosition( object.matrixWorld ), camera );

vector.x = ( vector.x * widthHalf ) + widthHalf;
vector.y = - ( vector.y * heightHalf ) + heightHalf;
22
votes

For modern Three.js (r75), a vector can be projected onto the screen with:

var width = window.innerWidth, height = window.innerHeight;
var widthHalf = width / 2, heightHalf = height / 2;

var pos = object.position.clone();
pos.project(camera);
pos.x = ( pos.x * widthHalf ) + widthHalf;
pos.y = - ( pos.y * heightHalf ) + heightHalf;
13
votes

For everyone getting deprecated or warnings logs, the accepted answer is for older Three.js versions. Now it's even easier with:

let pos = new THREE.Vector3();
pos = pos.setFromMatrixPosition(object.matrixWorld);
pos.project(camera);

let widthHalf = canvasWidth / 2;
let heightHalf = canvasHeight / 2;

pos.x = (pos.x * widthHalf) + widthHalf;
pos.y = - (pos.y * heightHalf) + heightHalf;
pos.z = 0;

console.log(pos);