Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

javascript - 3d coordinates to 2d screen position

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);

}

I had to change the projector to vector.project and matrixWorld.getPosition().clone() to position.clone().

passing position (0,0,0) results with v = {x: NaN, y: NaN, z: -Infinity}, which is not what expected

camera which im passing is camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 1, 10000 )

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...