简体   繁体   English

在Three.js项目中计算top,left,width,height

[英]Compute top,left,width,height in Three.js projetion

I'm struggling with a problem: I need to position a DIV over a WebGL animation. 我遇到了一个问题:我需要在WebGL动画上放置DIV。 I rotate a mesh , based on a PlaneGeometry to occupy a rectangular size, then I'd like top position there the DIV, so I need to know what is the X,Y coordinate and the rendered dimensions of the plane. 我基于PlaneGeometry旋转mesh以占据矩形大小,然后希望DIV处于顶部位置,因此我需要知道X,Y坐标和平面的渲染尺寸。

在此处输入图片说明

I've tried the THREE.Projection class, but didn't help, even if I projected the [0] verticle using .projectVector . 我已经尝试过THREE.Projection类,但是即使我使用.projectVector投影了[0] THREE.Projection也没有帮助。 It computed: 计算得出:

x: -0.1994540991160383
y: 0.17936202821347358
z: 0.9970982652556688

...which was little help to me. ...这对我无济于事。

To project a 3D point position to screen coordinates, relative to the renderer's canvas, do this: 要将3D点position投影到相对于渲染器画布的屏幕坐标,请执行以下操作:

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 is, in this case, renderer.domElement . 在这种情况下, canvasrenderer.domElement

A point in the upper left corner of your visible world will project to ( 0, 0 ). 可见世界左上角的点将投影为(0,0)。

three.js r.53 three.js r.53

I found the solution. 我找到了解决方案。 The top left point is indeed the 0 index of the plane 's vertices, but you have to take into account the already performed transformations as well. 左上角的确是plane顶点的0索引,但是您还必须考虑已经执行的转换。

function calculateLayer()
{
    // multiplyVector3 applies the performed transformations to the object's 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 once you have the correct coordinates, applied with the transformations, you just have to use the 3d to 2d conversion thanks to WestLangley. 因此,一旦有了正确的坐标并进行了转换,由于使用了WestLangley,您只需使用3d到2d转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM