如何在 THREE.js 中获取被点击的元素 [英] how to get clicked element in THREE.js

查看:52
本文介绍了如何在 THREE.js 中获取被点击的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在画布中有一些元素,它们可能会被彼此覆盖.当点击一个点时,我怎样才能得到那个元素?

Say I have some elements in the canvas, they may be overridden with each other. When clicking on a point, how can I get that very element?

更新:这个演示很有帮助:http://mrdoob.github.com/three.js/examples/canvas_interactive_cubes.html

推荐答案

使用以下代码.这将允许您添加点击事件并在发生这种情况时执行您需要的操作.你可以查看页面的源代码,看看他们在做什么,这是我从那里得到的代码.

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 );
    }
    */
}

这篇关于如何在 THREE.js 中获取被点击的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆