how to Get CLICKED element in THREE.js

Question!

I have many elements in the canvas using THREE.js,

they may be override with each others.

so now, when click on a point,

how can i get that very element?

update: guys, this demo helps a lot: http://mrdoob.github.com/three.js/examples/canvas_interactive_cubes.html

By : Nano WANG


Answers
Use the following code. This will allow you to add a click event and do what you need to when that happens. You can view the source of the page to see what they are doing which is were I got this code from.

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

var projector = new THREE.Projector();

function onDocumentMouseDown( event ) {

    event.preventDefault();

    var vector = new THREE.Vector3(
        ( event.clientX / window.innerWidth ) * 2 - 1,
      - ( event.clientY / window.innerHeight ) * 2 + 1,
        0.5
    );
    projector.unprojectVector( vector, camera );

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

    var intersects = ray.intersectObjects( objects );

    if ( intersects.length > 0 ) {

        intersects[ 0 ].object.materials[ 0 ].color.setHex( Math.random() * 0xffffff );

        var particle = new THREE.Particle( particleMaterial );
        particle.position = intersects[ 0 ].point;
        particle.scale.x = particle.scale.y = 8;
        scene.add( particle );

    }

    /*
    // Parse all the faces
    for ( var i in intersects ) {
        intersects[ i ].face.material[ 0 ].color
            .setHex( Math.random() * 0xffffff | 0x80000000 );
    }
    */
}


The example you link to has a simple API for this.

Put this in your HTML. You'll have to download the script and make sure it loads.

<script src='threex.domevent.js'></script>

Then, on your mesh object, call the following:

mesh.on('click', function()
{
    // response to click...
    mesh.scale.x *= 2;
});

Or a more interesting example that animates the rotation and color of an object smoothly:

mesh.on('click', function(event)
{
    var object3d = event.target,
        rotation, color;
    if (object3d.rotation.x < Math.PI / 4) {
        rotation = {x: Math.PI / 2};
        color = {r: 1, g: 0.5, b: 0};
    } else {
        rotation = {x: 0};
        color = {r: 0.5, g: 0.75, b: 0.25};
    }
    new TWEEN.Tween(object3d.rotation)
        .to(rotation, 800)
        .easing(TWEEN.Easing.Bounce.EaseOut)
        .start();
    new TWEEN.Tween(object3d.material.color)
        .to(color, 300)
        .easing(TWEEN.Easing.Quartic.EaseIn)
        .start();
})


This video can help you solving your question :)
By: admin