javascripthtmlthree.js

THREE.js Ray Intersect fails by adding div


My Three.js script runs fine when there is only one target div on the page (which holds renderer.domElement). As soon as I add another div with fixed height and width above the target div, ray.intersectObjects returns null. I doubt that the vector that I am creating for ray is causing the problem. Here is the code.

var vector = new THREE.Vector3( ( event.clientX / divWidth ) * 2 - 1, -( event.clientY / divHeight ) * 2 + 1, 0.5 );

projector.unprojectVector( vector, camera );

var ray = new THREE.Ray( camera.position, vector.subSelf( camera.position ).normalize() );

var intersects = ray.intersectObjects( myObjects, true );

Any ideas on how I can solve this.

EDIT: it is now THREE.Raycaster (three.js r.56)


Solution

  • The short answer is you have to take into consideration the offset of the canvas.

    The long answer depends on how your code is written, so I'll give you two answers, which should cover the bases.

    Assume your HTML is something like this:

    <style>
        #canvas {
            width: 200px;
            height: 200px;
            margin: 100px;
            padding: 0px;
            position: static; /* fixed or static */
            top: 100px;
            left: 100px;
        }
    </style>
    
    <body>
        <div id="canvas"></div>
    </body>
    

    Your JS is something like this:

    const CANVAS_WIDTH = 200,
    CANVAS_HEIGHT = 200;
    
    const container = document.getElementById( 'canvas' );
    document.body.appendChild( container );
    
    const renderer = new THREE.WebGLRenderer();
    renderer.setPixelRatio( window.devicePixelRatio );
    renderer.setSize( CANVAS_WIDTH, CANVAS_HEIGHT );
    container.appendChild( renderer.domElement );
    

    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.clientWidth ) * 2 - 1;
    mouse.y = - ( ( event.clientY - renderer.domElement.offsetTop ) / renderer.domElement.clientHeight ) * 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;
    

    Here is a Fiddle if you want to experiment: https://jsfiddle.net/uf4c0ws9/

    EDIT: Fiddle updated to three.js r.150