I use CSS2DRenderer to put labels on object in the scene. This works pretty well.
But if I rotate the object in the scene, labels goes outside the scene in an area devoted to controls (see attached image).
Is there a way to hide labels that goes outside the scene?
Thanks!
CSS2DRenderer does not automatically clip elements to the canvas area because the labels are actually regular HTML elements positioned on top of the WebGL canvas. When the projected position of the object goes outside the camera view, the DOM element can still end up rendered outside the visible canvas area.
One simple approach is to check if the label’s projected position is inside the screen bounds and hide it if it is not. You can project the 3D position to normalized device coordinates and then toggle visibility.
Example idea:
const pos = object.position.clone();
pos.project(camera);
const visible =
pos.x >= -1 && pos.x <= 1 &&
pos.y >= -1 && pos.y <= 1 &&
pos.z >= -1 && pos.z <= 1;
label.element.style.display = visible ? “block” : “none”;
Another option is to control it with CSS by clipping the label container so anything outside the canvas area is hidden. For example by putting the renderer DOM element inside a container with overflow hidden.
Many projects combine both methods. The projection check avoids unnecessary DOM updates, and CSS clipping ensures labels do not appear outside the intended viewport.
@Umbawa_Sarosong Thanks for the suggestions! I already have put the overflow hidden without success.
My problem was the height of the canvas area that was the height of the full window. Now reduced it by the height of the control strip below and everything is correct now.
Setting the label visibility is also a good suggestion for the future. Now the labels are not so many to consider them a performance problem.
Have a nice day!