Threejs,了解raycaster的交叉对象坐标

时间:2018-03-20 20:20:48

标签: javascript three.js click raycasting

您好,我有一个疑问:

我已经实施了一个raycaster并且我一直在手动测试它,但是我不知道为什么在我对3D模型进行的大多数点击中,它没有得到交叉点。

首先,我将向您展示我点击的点数,然后是Web控制台中记录的点数,然后是我实施的代码,最后是网络结构:

我点击了这八点:

enter image description here

结果是:

[]length: 0__proto__: Array(0)
[]length: 0__proto__: Array(0)
[]length: 0__proto__: Array(0)
[]length: 0__proto__: Array(0)
point: Vector3 x:--99.34871894866089 y:67 z:0
point: Vector3 x: -126.50880038786315 y: 73.48094335146214 z: -5.684341886080802
[]length: 0__proto__: Array(0)
[]length: 0__proto__: Array(0)

这里我们有实现的代码,重要的部分是onDocumentMouseDown函数:

if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

// global variables for this scripts
let OriginalImg, 
    SegmentImg;

var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var mousePressed = false;



init();
animate();


// initilize the page
function init ()
{
    let filename = "models/nrrd/columna01.nrrd"; // change your nrrd file
    let idDiv = 'original';
    OriginalImg = new InitCanvas(idDiv, filename );
    OriginalImg.init();
    console.log(OriginalImg);

    filename = "models/nrrd/columnasegmentado01.nrrd"; // change your nrrd file
    idDiv = 'segment';
    SegmentImg = new InitCanvas(idDiv, filename );
    SegmentImg.init(); 
}

document.addEventListener( 'mousedown', onDocumentMouseDown, false );
document.addEventListener( 'mouseup', onDocumentMouseUp, false );

function onDocumentMouseDown( event ) {
    mousePressed = true;
    mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
    mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
    raycaster.setFromCamera( mouse.clone(), OriginalImg.camera );
    var objects = raycaster.intersectObjects(OriginalImg.scene.children);
    console.log(objects);
}
function onDocumentMouseUp( event ) { mousePressed = false}





function animate() {


    requestAnimationFrame( animate );
    OriginalImg.animate();
    SegmentImg.animate();


}   

我们在这里看到网络结构:

enter image description here

我怀疑由于画布在窗口中有偏移,因此我们点击的区域无法有效地获取这些点。

我也读过:

Debug threejs raycaster mouse coordinates

How do I get the coordinates of a mouse click on a canvas element?

https://threejs.org/docs/#api/core/Raycaster

threejs raycasting does not work

任何帮助都将受到赞赏,包括进一步阅读,理论建议和代码示例。

编辑:

1)我已经打开了一个具有相同主题和更详细的图像,图形和日志的新线程。这是链接:ThreeJS, raycaster gets strange coordinates when we log the intersection object

2)我按照@TheJim01提供的答案这里是当前的代码:

logic.js

if (!Detector.webgl) Detector.addGetWebGLMessage();

// global variables for this scripts
let OriginalImg,
    SegmentImg;

var mouse = new THREE.Vector2();
var raycaster = new THREE.Raycaster();
var mousePressed = false;
var clickCount = 0;


init();
animate();


// initilize the page
function init() {
    let filename = "models/nrrd/columna01.nrrd"; // change your nrrd file
    let idDiv = 'original';
    OriginalImg = new InitCanvas(idDiv, filename);
    OriginalImg.init();
    console.log(OriginalImg);

    filename = "models/nrrd/columnasegmentado01.nrrd"; // change your nrrd file
    idDiv = 'segment';
    SegmentImg = new InitCanvas(idDiv, filename);
    SegmentImg.init();
}

let originalCanvas = document.getElementById('original');
originalCanvas.addEventListener('mousedown', onDocumentMouseDown, false);
originalCanvas.addEventListener('mouseup', onDocumentMouseUp, false);


function onDocumentMouseDown(event) {
    mousePressed = true;

    clickCount++;


    mouse.x = ( event.offsetX / window.innerWidth ) * 2 - 1;
    console.log('Mouse x position is: ', mouse.x, 'the click number was: ', clickCount);
    mouse.y = -( event.offsetY / window.innerHeight ) * 2 + 1;
    console.log('Mouse Y position is: ', mouse.y);
    raycaster.setFromCamera(mouse.clone(), OriginalImg.camera);
    var objects = raycaster.intersectObjects(OriginalImg.scene.children);
    console.log(objects);
}

function onDocumentMouseUp(event) {
    mousePressed = false
}


function animate() {


    requestAnimationFrame(animate);
    OriginalImg.animate();
    SegmentImg.animate();


}   

InitCanvas.js

// this class handles the load and the canva for a nrrd
// Using programming based on prototype: https://javascript.info/class
// This class should be improved:
//   - Canvas Width and height

InitCanvas = function ( IdDiv, Filename ) {


    this.IdDiv = IdDiv;
    this.Filename = Filename
}

InitCanvas.prototype = {

    constructor: InitCanvas,

    init: function() {

        this.container = document.getElementById( this.IdDiv );

        // this should be changed.
        debugger;
        this.container.innerHeight = 600;
        this.container.innerWidth = 800;

        //These statenments should be changed to improve the image position
        this.camera = new THREE.PerspectiveCamera( 60, this.container.innerWidth / this.container.innerHeight, 0.01, 1e10 );
        this.camera.position.z = 300;

        let scene = new THREE.Scene();
        scene.add( this.camera );

        // light

        let dirLight = new THREE.DirectionalLight( 0xffffff );
        dirLight.position.set( 200, 200, 1000 ).normalize();

        this.camera.add( dirLight );
        this.camera.add( dirLight.target );


        // read file

        let loader = new THREE.NRRDLoader();
        loader.load( this.Filename , function ( volume ) {

            //z plane
            let sliceZ = volume.extractSlice('z',Math.floor(volume.RASDimensions[2]/4));

            debugger;
            this.container.innerWidth = sliceZ.iLength;
            this.container.innerHeight = sliceZ.jLength;

            scene.add( sliceZ.mesh );
        }.bind(this) );


        this.scene = scene;

        // renderer

        this.renderer = new THREE.WebGLRenderer( { alpha: true } );
        this.renderer.setPixelRatio( this.container.devicePixelRatio );
        debugger;
        this.renderer.setSize( this.container.innerWidth, this.container.innerHeight );

        // add canvas in container
        this.container.appendChild( this.renderer.domElement );

    },

    animate: function () {

        this.renderer.render( this.scene, this.camera );
    }

}

的index.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>Prototype: three.js without react.js</title>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0">
        <link rel="stylesheet" href="css/styles.css">

        <!-- load the libraries and js -->
        <script src="js/libs/three.js"></script>

        <script src="js/Volume.js"></script>
        <script src="js/VolumeSlice.js"></script>
        <script src="js/loaders/NRRDLoader.js"></script>

        <script src="js/Detector.js"></script>
        <script src="js/libs/stats.min.js"></script>
        <script src="js/libs/gunzip.min.js"></script>
        <script src="js/libs/dat.gui.min.js"></script>

        <script src="js/InitCanvas.js"></script>


    </head>

    <body>
        <div id="info">
            <h1>Prototype: three.js without react.js</h1> 
        </div>

        <!-- two canvas -->
        <div class="row">
            <div class="column" id="original">
            </div>

            <div class="column" id="segment">

            </div>
          </div> 

        <script src="js/logic.js"></script>

    </body>
</html>

我确信它确实有不同的作用。到目前为止,我知道画布坐标的原点是全屏模式下的红色坐标,当我们打开右侧的Chrome开发工具时,它是绿色的:

enter image description here

此外,raycaster接受ThreeJS模型的区域是全屏的红色区域,当我们打开下面的Mozilla开发工具时是绿色区域:

enter image description here

3)目前,画布是从名为div的父div创建的,它是:

enter image description here

在其中创建的画布是800x600

enter image description here

我们怎么能实现raycaster的拦截区成为画布&#39;模特的大小?

5)为了能够解决自己的困难,我研究了这个好的SO帖子: THREE.js Ray Intersect fails by adding div

但是我看到在我链接的帖子中,@ WestLangley使用clientX,Y和答案部分@TheJim01建议使用offsetX,Y。

另外,由于我是ThreeJS的初学者,而且我一直在学习JS,但是我遇到了一些困难:

如何在浏览器中处理坐标原点?

three.js中坐标的来源是什么?

两者如何相关?

为什么大多数文章都使用这个表达式?:

mouse.x = ( event.offsetX / window.innerWidth ) * 2 - 1;

为什么我们需要除以window.innerWidth?我们做* 2 - 1

6)我问这一切是因为我想做一个Web应用程序,我们可以收集用户点击左侧画布的点,然后我们在右侧画布上更改相同部分的颜色,并且我们会显示一些有关它的信息作为名称和描述。

然后使用ThreeJS收集鼠标点击位置非常重要,可以使用它来更改右侧画布和单击部分上的颜色。

7)另外我还读过:

Update Three.js Raycaster After CSS Tranformation

EDIT2:22/03/18

我已经按照@WestLangley提供的答案:THREE.js Ray Intersect fails by adding div

它允许我们在画布上拥有raycaster的交叉区域&#39;图像。

所以它在实践中解决了这个问题。

然而,我仍然不理解某些东西,例如浏览器和Threejs&#39;之间的关系。坐标。

在这里我们看到在浏览器和ThreeJS&#39; raycaster截取的对象,x坐标是相同的,但是Y坐标是不同的,为什么?

enter image description here

此外,我怀疑浏览器在画布上的坐标原点位于中心位置:

enter image description here

这是正确的吗?

我将展示我需要添加的代码片段,以使raycaster的检测区域与canvas&#39;相同。图像。

首先我在CSS中添加了:

canvas {
    width: 200px;
    height: 200px;
    margin: 100px;
    padding: 0px;
    position: static; /* fixed or static */
    top: 100px;
    left: 100px;
}

然后我添加了logic.js

function onDocumentMouseDown(event) {
    mousePressed = true;

    clickCount++;

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

    console.log('Mouse x position is: ', mouse.x, 'the click number was: ', clickCount);
    console.log('Mouse Y position is: ', mouse.y);

    raycaster.setFromCamera(mouse.clone(), OriginalImg.camera);
    var objects = raycaster.intersectObjects(OriginalImg.scene.children);

    console.log(objects);
}

如上所示,我在鼠标x和y上添加了偏移量Left和Top,除以渲染器Width / Height。

此外,我还研究了如何在OpenAnatomy中完成鼠标点击:

function onSceneMouseMove(event) {

        //check if we are not doing a drag (trackball controls)
        if (event.buttons === 0) {
            //compute offset due to container position
            mouse.x = ( (event.clientX-containerOffset.left) / container.clientWidth ) * 2 - 1;
            mouse.y = - ( (event.clientY-containerOffset.top) / container.clientHeight ) * 2 + 1;

            needPickupUpdate = true;
        }
        else {
            needPickupUpdate = false;
        }
}

链接:https://github.com/mhalle/oabrowser/blob/gh-pages/src/app.js

所以我们看到它们也使用偏移量,左边和顶部,除以宽度和高度,但这次是容器中的那些而不是渲染器。

我也在AMI研究了他们是如何做到的:

function onDoubleClick(event) {
      const canvas = event.target.parentElement;
      const id = event.target.id;
      const mouse = {
        x: ((event.clientX - canvas.offsetLeft) / canvas.clientWidth) * 2 - 1,
        y: - ((event.clientY - canvas.offsetTop) / canvas.clientHeight) * 2 + 1,
};

链接:https://github.com/FNNDSC/ami/blob/dev/examples/viewers_quadview/viewers_quadview.js

所以在这里我们看到,而不是容器甚至是渲染器,它们使用画布本身的偏移量。

此外,我已经研究了一些官方的ThreeJS示例,它们看起来只有一个全屏渲染器/场景,因此他们没有展示如何在同一个网页中处理各种画布和射线播放器。

    function onDocumentMouseMove( event ) {
        event.preventDefault();
        mouse.x = ( event.clientX / window.innerWidth ) * 2 - 1;
        mouse.y = - ( event.clientY / window.innerHeight ) * 2 + 1;
    }

链接:https://github.com/mrdoob/three.js/blob/master/examples/webgl_interactive_cubes.html

function onMouseMove( event ) {
                mouse.x = ( event.clientX / renderer.domElement.clientWidth ) * 2 - 1;
                mouse.y = - ( event.clientY / renderer.domElement.clientHeight ) * 2 + 1;
                raycaster.setFromCamera( mouse, camera );
                // See if the ray from the camera into the world hits one of our meshes
                var intersects = raycaster.intersectObject( mesh );
                // Toggle rotation bool for meshes that we clicked
                if ( intersects.length > 0 ) {
                    helper.position.set( 0, 0, 0 );
                    helper.lookAt( intersects[ 0 ].face.normal );
                    helper.position.copy( intersects[ 0 ].point );
                }
            }

链接:https://github.com/mrdoob/three.js/blob/master/examples/webgl_geometry_terrain_raycast.html

你能帮我吗?

谢谢。

1 个答案:

答案 0 :(得分:1)

Raycarster.setFromCamera(NDC, camera)以标准化设备坐标为第一个参数。那是一个介于-1和1之间的值。但是您要给出实际的坐标。这就是为什么它不相交的原因。试试这个:

const screenPosition = {
        x: event.clientX - canvas.offsetLeft,
        y: event.clientY - canvas.offsetHeight
};
const widthHalf = canvas.clientWidth * 0.5;
const heightHalf = canvas.clientHeight * 0.5;
const mouse = {
        x: (screenPosition.x - widthHalf) / widthHalf ,
        y: - (screenPosition.y - heightHalf) / heightHalf,
};

还尝试在true中将递归设置为intersectObject()