Selecting an object from the small three.js viewport

I can display a full view of graphical objects with three .js and use a mouse click on an object to select an object.

But if I try to display the three.js graphic in a small viewport on the html page, I get problems. To calculate the coordinates of the viewpoint of the mouse position by the coordinates of the screen, I need to know the value of the pixel offsets of the left frame window and the top view window.

Then I can use a coordinate transformation algorithm such as (changed from http://stemkoski.github.com/Three.js/Mouse-Tooltip.html ): -

mouse.x =   ( (event.clientX - viewport_OffsetLeft_X) / viewport_Width) * 2 - 1;
mouse.y = - ( (event.clientY- viewport_OffsetTop_Y) / viewport_Height ) * 2 + 1;

But my question is: how to get the offset values ​​in the viewport? Note. I need to do this at runtime without checking the values ​​from the debugger and then hard-wiring them to the code.

Any suggestions gratefully received!

0
source share
2 answers

There are two main ways to find the offsets of your canvas from the top of the screen.

The following code from West Langley illustrates: Method 1 To correctly use the following method, set the canvas position to static; margin> 0 and padding> 0 in order

mouse.x = ((event.clientX - renderer.domElement.offsetLeft) /renderer.domElement.width) * 2 - 1; mouse.y = - ((event.clientY - renderer.domElement.offsetTop) /renderer.domElement.height) * 2 + 1;

2 ; set top > 0, left > 0; 0; margin > 0

mouse.x = ((event.clientX - container.offsetLeft)/container.clientWidth) * 2 - 1; mouse.y = - ((event.clientY - container.offsetTop)/container.clientHeight) * 2 + 1;

. - , html iframe html.

+1

var x, y, top = 0, left = 0, obj = document.getElementById('canvas');
        var objWebGl = document.getElementById('canvas');

        while (obj && obj.tagName !== 'BODY') {

            top += obj.offsetTop;
            left += obj.offsetLeft;
            obj = obj.offsetParent;
        }

        left += window.pageXOffset;
        top -= window.pageYOffset;

        x = ((event.clientX - left) / objWebGl.clientWidth) * 2 - 1;
        y = -((event.clientY - top) / objWebGl.clientHeight) * 2 + 1;

        var vector = new THREE.Vector3(x, y, 0.5);
0

Source: https://habr.com/ru/post/1537423/


All Articles