Calculate top, left, width, height in Three.js project

I am struggling with a problem: I need to place a DIV over a WebGL animation. I rotate a mesh

based on PlaneGeometry

to take a rectangular size, then I would like the top position to be a DIV, so I need to know what the X, Y coordinate and rendered dimensions of the plane are.

enter image description here

I tried the class THREE.Projection

but didn't help even if I was projecting the [0]

verticle with .projectVector

. He calculated:

x: -0.1994540991160383
y: 0.17936202821347358
z: 0.9970982652556688

      

... which helped me a little.

+1


source to share


2 answers


To project a 3D point position

to screen coordinates relative to the render canvas, do the following:

var projector = new THREE.Projector();
var pos = projector.projectVector( position, camera );

var xcoord = Math.round( (  pos.x + 1 ) * canvas.width  / 2 );
var ycoord = Math.round( ( -pos.y + 1 ) * canvas.height / 2 );

      

where canvas

, in this case renderer.domElement

.



The point in the upper left corner of the visible world will be projected onto (0, 0).

three.js r.53

0


source


I found a solution. The top-left point is indeed the vertex index 0 plane

, but you must also consider the transformations already performed.

function calculateLayer()
{
    // multiplyVector3 applies the performed transformations to the object coordinates.
    var topLeft = tubeCard.matrixWorld.multiplyVector3( tubeCard.geometry.vertices[0].clone() );
    // index 24 is the bottom right, because the plane has 4x4 faces
    var bottomRight = tubeCard.matrixWorld.multiplyVector3( tubeCard.geometry.vertices[24].clone() );
    return {
            topLeft: convert3Dto2D( topLeft ),
            bottomRight: convert3Dto2D( bottomRight )
        }
}

function convert3Dto2D( positionVector )
{
    var projector = new THREE.Projector();
    var pos = projector.projectVector( positionVector, camera );

    var xcoord = Math.round( (  pos.x + 1 ) * window.innerWidth  / 2 );
    var ycoord = Math.round( ( -pos.y + 1 ) * window.innerHeight / 2 );

    return { x: xcoord, y: ycoord };
}

      



So, if you have the correct coordinates applied to transforms, you just need to use 3d to 2d transform thanks to WestLangley.

0


source







All Articles