Converting World coordinates to Screen coordinates in Three.js using Projection
Solution 1:
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;
Solution 2:
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;
Solution 3:
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);