将 3D 位置转换为 2d 屏幕位置 [r69!] [英] Converting 3D position to 2d screen position [r69!]
问题描述
我需要 Three.js 代码将 3D 对象坐标转换为 'div' 元素中的 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:
这里是一些较新的代码 (?) 的片段,它没有为我提供足够的上下文来开始工作,但看起来更清晰:
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<轻松转换为屏幕位置/code> 函数,它更新 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';
这篇关于将 3D 位置转换为 2d 屏幕位置 [r69!]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!