My goal is to develop an interactive GUI for my app using threejs. I came across this informative tutorial:
The tutorial provides the exact information I need, but it refers to an older release.
function getCoordinates(element, camera) {
var p, v, percX, percY, left, top;
var projector = new THREE.Projector();
// This function will give us position relative to the world
p = element.position.clone();
console.log('projected position', p);
// The projectVector translates the 3D position to 2D
v = p.project(camera);
console.log('projected vector', v);
// Translating our vector so that percX=0 represents
// the left edge, percX=1 is the right edge,
// percY=0 is the top edge, and percY=1 is the bottom edge.
percX = (v.x + 1) / 2;
percY = (-v.y + 1) / 2;
// Scaling these values to our viewport size
left = percX * window.innerWidth;
top = percY * window.innerHeight;
console.log('2d coordinates left', left);
console.log('2d coordinates top', top);
}
I had to update projector
to vector.project
and
matrixWorld.getPosition().clone()
to position.clone()
.
When passing position (0,0,0)
, I noticed that
v = {x: NaN, y: NaN, z: -Infinity}
, which was not expected.
The camera being passed is
camera = new THREE.PerspectiveCamera(75, window.innerWidth/window.innerHeight, 1, 10000)
.