尝试使用threejs为我的应用创建交互式GUI。 我找到了这个教程: http://zachberry.com/blog/tracking-3d-objects-in-2d-with-three-js/
它确切地解释了我需要什么,但使用了一些旧版本。
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()
。
传递位置(0,0,0)
的结果为v = {x: NaN, y: NaN, z: -Infinity}
,这不是预期的
我通过的相机是camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 )
答案 0 :(得分:2)
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 );
}