Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
19
rated 0 times [  24] [ 5]  / answers: 1 / hits: 19406  / 12 Years ago, wed, july 18, 2012, 12:00:00

I have a 3D object with the position(x,y,z). How can I calculate the screen position(x,y) of that object?



I have search for it and one solution is that I have to find out the projection matrix then multiply 3D position point by this matrix to project it onto some 2D viewing surface (computer screen). But I have no idea how to find this matrix in Three.js.



I try a convert function like this but it give incorrect result



function Point3DToScreen2D(point3D){
var screenX = 0;
var screenY = 0;
var inputX = point3D.x - camera.position.x;
var inputY = point3D.y - camera.position.y;
var inputZ = point3D.z - camera.position.z;
var aspectRatio = renderer.domElement.width / renderer.domElement.height;
screenX = inputX / (-inputZ * Math.tan(camera.fov/2));
screenY = (inputY * aspectRatio) / (-inputZ * Math.tan(camera.fov / 2));
screenX = screenX * renderer.domElement.width;
screenY = renderer.domElement.height * (1-screenY);
return {x: screenX, y: screenY};
}


Thank in advance.


More From » three.js

 Answers
50

I make it done by this code at last:



Note: div parameter = canvas dom element.



function toScreenXY( position, camera, div ) {
var pos = position.clone();
projScreenMat = new THREE.Matrix4();
projScreenMat.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
projScreenMat.multiplyVector3( pos );

var offset = findOffset(div);

return { x: ( pos.x + 1 ) * div.width / 2 + offset.left,
y: ( - pos.y + 1) * div.height / 2 + offset.top };

}
function findOffset(element) {
var pos = new Object();
pos.left = pos.top = 0;
if (element.offsetParent)
{
do
{
pos.left += element.offsetLeft;
pos.top += element.offsetTop;
} while (element = element.offsetParent);
}
return pos;
}

[#84187] Tuesday, July 17, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tomas

Total Points: 165
Total Questions: 111
Total Answers: 103

Location: Maldives
Member since Tue, Dec 21, 2021
2 Years ago
tomas questions
Thu, Jan 27, 22, 00:00, 2 Years ago
Mon, May 10, 21, 00:00, 3 Years ago
Tue, Jan 5, 21, 00:00, 3 Years ago
;