2

I have been developing a rough diagramming tool using THREE.js and have been using the THREE.js CSS2D facility to make (rotatable and MathJax-friendly) text labels for the diagrams.

I have implemented object picking for ordinary mesh objects (e.g. cubes, spheres, lines) using the THREE.js raycaster and it works fine. The mouse pointer changes to the text cursor when it is over a CSS2D text label. However raycaster does not pick any of the CSS2D label objects. Instead it "sees through" the labels and will pick a mesh object if one happens to be on the far side of the label.

I wonder if anyone can tell me whether object picking for CSS2D objects is feasible and what I might need to do to get it working?

steveOw
  • 879
  • 12
  • 41
  • It is hard to imagine it without an example. Can you provide a [minimally reproducible example](https://stackoverflow.com/help/minimal-reproducible-example)? – adelriosantiago Nov 26 '20 at 06:16
  • 1
    You can add event listeners to divs of CSS2DObject. AFAIK, `THREE.Raycaster` is not intended to work with CSS2DObject, CSS3DObject, as these objects don't have implementation of `raycast` method. – prisoner849 Nov 26 '20 at 07:09
  • @adelriosantiago Thanks, I'm currently trying out Mugen87's answer. If that doesnt work I'll maybe make an MRE. In the meantime here are official THREE.js examples of :- [CSS2D labels](https://threejs.org/examples/?q=css2d#css2d_label) and [Raycasting](https://threejs.org/examples/?q=raycast#webgl_interactive_cubes_ortho). – steveOw Nov 26 '20 at 10:45
  • @prisoner849. Thanks for your tips. Mugen87's answer reinforces them. – steveOw Nov 26 '20 at 10:47

1 Answers1

4

An instance of CSS2DObject is always a wrapper around HTML markup. That means you can simply add event listeners to the top most HTML element in order to detect interaction:

const text = document.createElement( 'div' );
text.className = 'label';
text.textContent = 'MyLabel';

text.addEventListener( 'pointerenter', event => console.log( event ) );

const label = new CSS2DObject( text );

Using THREE.Raycaster is not supported with CSS2DObject.

Mugen87
  • 28,829
  • 4
  • 27
  • 50
  • 1
    That works great, thanks. I'm using the child_Div trick of Jcastro to enable label rotation ( see his answer on [this page](https://stackoverflow.com/questions/64839541/three-js-how-to-rotate-css2d-text-labels) ) so I have to add the EventListener to that child_Div instead. To retrieve the text of the label I use: ` event => console.log( event.originalTarget.childNodes[0].childNodes[0].data ) ) `. – steveOw Nov 26 '20 at 11:45