Three.js: converting 3d position to 2d screen position

后端 未结 3 403
一向
一向 2020-11-30 10:59

I have a 3D object with the position(x,y,z). How can I calculate the screen position(x,y) of that object?

I have search for it and one solution is that I have to fin

3条回答
  •  温柔的废话
    2020-11-30 11:25

    I make it done by this code at last:

    Note: div parameter = canvas dom element.

    function toScreenXY( position, camera, div ) {
                var pos = position.clone();
                projScreenMat = new THREE.Matrix4();
                projScreenMat.multiply( camera.projectionMatrix, camera.matrixWorldInverse );
                projScreenMat.multiplyVector3( pos );
    
                var offset = findOffset(div);
    
                return { x: ( pos.x + 1 ) * div.width / 2 + offset.left,
                     y: ( - pos.y + 1) * div.height / 2 + offset.top };
    
            }
    function findOffset(element) { 
              var pos = new Object();
              pos.left = pos.top = 0;        
              if (element.offsetParent)  
              { 
                do  
                { 
                  pos.left += element.offsetLeft; 
                  pos.top += element.offsetTop; 
                } while (element = element.offsetParent); 
              } 
              return pos;
            } 
    

提交回复
热议问题