Three.js:三维位置转换到2D画面位置[R69!]位置、画面、Three、js

2023-09-08 09:05:35 作者:我的天拉鲁

[我在这里的第一个帖子,这说明我的绝望花费很多时间寻找答案,在这里和其他地方后]

[my first posting here, which shows my desperation after spending many hours searching for answers here and other places]

需要:Three.js code转换成3D物体坐标的二维那些在'DIV'的元素,这样我可以把文本标签,他们需要的是(如果没有这些标签的缩放/移动/随转三维运动)。不幸的是,和我懊恼的是,所有这一切我已经看到了,并试图到目前为止的例子似乎可以用废弃的功能/技术(这是常见的Three.js?)。就我而言,我相信我使用Three.js的R69。

Needed: Three.js code to convert 3d object coordinates to 2d ones in a 'div' element so that I can place text labels where they need to be (without those labels scaling/moving/rotating along with the 3d movement). Unfortunately, and to my chagrin, all of the examples that I have seen and tried so far seem to be using obsolete functions/techniques (is this common with Three.js?). In my case, I believe that I am using r69 of Three.js.

下面是刚刚产生的错误对我来说,旧技术的一个例子:

Here is an example of an 'older' technique that just produces errors for me:

Three.js:三维位置转换到2D屏幕位置

下面是一些较新的code一个片段,没有提供足够的情况下,我得到的工作,但看起来有很多清洁剂(?):

Here is a snippet of some newer code (?) that doesn't provide sufficient context for me to get working, but looks a lot cleaner:

https://github.com/mrdoob/three.js/issues/5533

谢谢!

推荐答案

我已经为我的项目下面的函数写的,它收到了Object3D和相机作为参数和返回屏幕上的位置。

I've written for my project the following function, it's received an Object3D and a camera as a parameters and return the screen position.

function toScreenPosition(obj, camera)
{
    var vector = new THREE.Vector3();

    var widthHalf = 0.5*renderer.context.canvas.width;
    var heightHalf = 0.5*renderer.context.canvas.height;

    obj.updateMatrixWorld();
    vector.setFromMatrixPosition(obj.matrixWorld);
    vector.project(camera);

    vector.x = ( vector.x * widthHalf ) + widthHalf;
    vector.y = - ( vector.y * heightHalf ) + heightHalf;

    return { 
        x: vector.x,
        y: vector.y
    };

};

然后,我创建THREE.Object3D仅仅是保持DIV位置(它连接到一些真正的目场景),并在需要的时候可以使用toScreenPosition功能和更新DIV的坐标很容易转化为屏幕上的位置。

Then i created THREE.Object3D just to hold the div position (it's attached to some real mesh in the scene) and when needed can easily converted to screen position using toScreenPosition function and update the div coordinate.

var proj = toScreenPosition(divObj, camera);

divElem.style.left = proj.x + 'px';
divElem.style.top = proj.y + 'px';

的jsfiddle: http://jsfiddle.net/kgxeuz24/7/