簡體   English   中英

3d 坐標到 2d 屏幕位置

[英]3d coordinates to 2d screen position

嘗試使用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 )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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM