How to use Event handlers on canvas not just the mesh #2135
-
From what I read here R3F offers built in event handlers. However as I understand, these events handlers are limited to the mesh. Is there an approach to using these on the canvas as well? I Have this code sandbox that runs a floating plane with functions triggered by mouse events (mouseUp, mouseDown, mouseMove). I ended up using regular event handlers on the document because I also need these functions to be triggered beyond the mesh, if I click outside the mesh anywhere on the canvas (which I styled it to cover the entire viewport) they also need to be triggered. What approach could I take to achieve this? Appreciate any feedback! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
With R3F v8 you're able to use react-dom's built-in synthetic events (onClick, etc.) among other props on the canvas, but I'd recommend using pointer events where you can. The following can be a re-usable component but you can target the canvas as well. const container = useRef()
useEffect(() => {
const onPointerUp = () => {}
const onPointerDown = () => {}
const onPointerMove = () => {}
container.current.addEventListener('pointerup', onPointerUp)
container.current.addEventListener('pointerdown', onPointerDown)
container.current.addEventListener('pointermove', onPointerMove)
return () => {
container.current.removeEventListener('pointerup', onPointerUp)
container.current.removeEventListener('pointerdown', onPointerDown)
container.current.removeEventListener('pointermove', onPointerMove)
}
}, [])
<div ref={container}>
<Canvas />
</div> |
Beta Was this translation helpful? Give feedback.
With R3F v8 you're able to use react-dom's built-in synthetic events (onClick, etc.) among other props on the canvas, but I'd recommend using pointer events where you can. The following can be a re-usable component but you can target the canvas as well.