将3D位置转换为2d屏幕位置[r69!] [英] Converting 3D position to 2d screen position [r69!]

查看:154
本文介绍了将3D位置转换为2d屏幕位置[r69!]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要Three.js代码在'div'元素中将3D对象坐标转换为2d对象,以便我可以将文本标签放置在需要放置它们的位置(没有那些标签随3D运动而缩放/移动/旋转) 。不幸的是,到目前为止,我已经看到并尝试过的所有示例似乎都在使用过时的功能/技术。就我而言,我相信我正在使用Three.js的r69。

I need 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, all of the examples that I have seen and tried so far seem to be using obsolete functions/techniques. 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:将3d位置转换为2d屏幕位置

以下是一些较新的代码(?)的片段,这些代码没有为我提供足够的上下文来开始工作,但看上去更干净:

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

推荐答案

我为我的项目编写了以下函数;它接收一个 THREE.Object3D 实例和一个相机作为参数,并返回屏幕上的位置。

I've written for my project the following function; it receives an THREE.Object3D instance and a camera as a parameters and returns the position on the screen.

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 a THREE.Object3D just to hold the div position (it's attached to a mesh in the scene) and when needed it can easily converted to screen position using the toScreenPosition function and it updates the coordinates of the div element.

var proj = toScreenPosition(divObj, camera);

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

在此处摆弄演示的小提琴

Here a fiddle with a demo.

这篇关于将3D位置转换为2d屏幕位置[r69!]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆