3d 坐标到 2d 屏幕位置 [英] 3d coordinates to 2d screen position
问题描述
尝试使用threejs为我的应用程序创建交互式GUI.我找到了这个教程:http://zachberry.com/blog/tracking-3d-objects-in-2d-with-three-js/
Trying to create interactive GUI for my app using threejs. I've found this tutorial: http://zachberry.com/blog/tracking-3d-objects-in-2d-with-three-js/
这正是我需要的,但使用了一些旧版本.
which explains exactly what I need, but uses some old release.
function getCoordinates(element, camera) {
var p, v, percX, percY, left, top;
var projector = new THREE.Projector();
// this will give us position relative to the world
p = element.position.clone();
console.log('project p', p);
// projectVector will translate position to 2d
v = p.project(camera);
console.log('project v', v);
// translate our vector so that percX=0 represents
// the left edge, percX=1 is the right edge,
// percY=0 is the top edge, and percY=1 is the bottom edge.
percX = (v.x + 1) / 2;
percY = (-v.y + 1) / 2;
// scale these values to our viewport size
left = percX * window.innerWidth;
top = percY * window.innerHeight;
console.log('2d coords left', left);
console.log('2d coords top', top);
}
我不得不将 projector
更改为 vector.project
并将 matrixWorld.getPosition().clone()
更改为 position.clone()
.
I had to change the projector
to vector.project
and matrixWorld.getPosition().clone()
to position.clone()
.
传递位置 (0,0,0)
结果为 v = {x: NaN, y: NaN, z: -Infinity}
,这不是预期的
passing position (0,0,0)
results with v = {x: NaN, y: NaN, z: -Infinity}
, which is not what expected
我通过的相机 camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 1, 10000 )
推荐答案
function getCoordinates( element, camera ) {
var screenVector = new THREE.Vector3();
element.localToWorld( screenVector );
screenVector.project( camera );
var posx = Math.round(( screenVector.x + 1 ) * renderer.domElement.offsetWidth / 2 );
var posy = Math.round(( 1 - screenVector.y ) * renderer.domElement.offsetHeight / 2 );
console.log( posx, posy );
}
http://jsfiddle.net/L0rdzbej/122/
这篇关于3d 坐标到 2d 屏幕位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!