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

后端 未结 3 390
一向
一向 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:03

    Check out the source at the demo: http://stemkoski.github.com/Three.js/Mouse-Over.html

    The object that I believe you are interested in is THREE.Projector(); you can use this, for example, for automating calculations that create rays from the location of mouse cursor on the screen and project it into the scene.

    0 讨论(0)
  • 2020-11-30 11:07

    For me this function works (Three.js version 69):

    function createVector(x, y, z, camera, width, height) {
            var p = new THREE.Vector3(x, y, z);
            var vector = p.project(camera);
    
            vector.x = (vector.x + 1) / 2 * width;
            vector.y = -(vector.y - 1) / 2 * height;
    
            return vector;
        }

    0 讨论(0)
  • 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;
            } 
    
    0 讨论(0)
提交回复
热议问题