object picking from small three.js viewport

一笑奈何 提交于 2019-12-04 20:55:51

There are two basic ways of finding out the offsets of your canvas from the screen origin.

The following code from West Langley illustrates:- Method 1 For the following method to work correctly, set the canvas position static; margin > 0 and padding > 0 are OK

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

Method 2 For this alternate method, set the canvas position fixed; set top > 0, set left > 0; padding must be 0; margin > 0 is OK

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

But you need to be careful about padding and margins. A way to reduce this trouble is by filling the screen and then accessing the resulting html page from an iframe in another html page.

My code looks like this

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);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!