【问题标题】:How to create click event listener on react-three-fiber / three.js?如何在 react-three-fiber/three.js 上创建点击事件监听器?
【发布时间】:2021-04-15 20:49:24
【问题描述】:

我正在尝试在我的 react-three-fiber 画布上监听点击事件。但是我在使用addEventListener 时遇到了不同的事件。

onClickmesh 属性返回以下事件:

      <mesh position={[0, 0, 0]} onClick={(e) => console.log('onClick mesh: ', e)}>
        <boxGeometry attach="geometry" args={[10, 10, 10]} />
        <meshStandardMaterial attach="material" color="hotpink" wireframe />
      </mesh>
onClick mesh:  
{dispatchConfig: Object, _targetInst: FiberNode, nativeEvent: MouseEvent, type: "click", target: Object…} 
// This is the event I need!!

添加事件监听器会返回以下事件:

const ThreeEventListener = () => {
  const onClickDocument = (e) => {
    console.log('onClick document listener: ', e)
  }
  useEffect(() => {
    document.addEventListener('click', onClickDocument, false)
    return () => document.removeEventListener('click', onClickDocument)
  })
  return null
}
onClick document listener:  
MouseEvent {isTrusted: true, screenX: 1508, screenY: 427, clientX: 348, clientY: 178…}
// This is a normal DOM event from React that I dont need

Demo(单击框触发事件)

【问题讨论】:

  • 三个没有事件,它们来自R3F,它监视通用指针事件,然后进行光线投射,并形成对象级事件。通过向画布添加事件侦听器,您将再次获得常规指针事件。但是,您为什么要这样做,因为您不应该触摸 dom。

标签: javascript reactjs three.js react-three-fiber


【解决方案1】:

我假设您第一次得到的是 SyntheticEvent 的实例,它作为对原生事件的包装器将 React uses 与一些对 react-three-fiber 字段有用的组合在一起 - 这里是 doc。文档说在他们的事件实现中有一个本机浏览器事件和 three.js 有用的数据(这是你收到的)。

我建议在合成事件中从原生事件中取出你需要的东西:

event.nativeEvent 

【讨论】:

    【解决方案2】:

    这是一个使用名为 three.interaction 的外部库的封闭解决方案:

    import { Interaction } from 'three.interaction'
    
    const ThreeEventListener = () => {
    
        useEffect(() => {
            // init three.interaction on mount
            const interaction = new Interaction(gl, scene, camera);
        }, [])
    
        const onClickScene = (event) => {
            console.log('onClick scene listener: ', e)
        }
    
        useEffect(() => {
            // attach callbacks to clicks thanks to three.interaction
            scene.on('click', onClickScene)
            return () => scene.on('click', () => {})
        })
    
        return null
    }
    

    three.interaction 创建的事件如下:

    onClick scene listener:  InteractionEvent {stopped: false, target: Scene, currentTarget: Scene, type: "click", data: InteractionData, …}
    

    【讨论】:

      猜你喜欢
      • 2021-05-22
      • 1970-01-01
      • 2021-10-03
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      • 1970-01-01
      • 2022-10-05
      • 2020-10-31
      相关资源
      最近更新 更多