Capítulo 800 de 859
How to project a 3D object's screen-space position so an overlaid HTML/CSS label (e.g. a name tag) tracks it, including handling occlusion and depth ordering.
Vector3.project(camera): converts a world position to normalized device coordinates (-1 to 1) for the current camera.Raycaster fired from the camera toward the object's position checks whether that object is the first hit, hiding the label if something else is in front.zIndex so nearer labels render on top of farther ones.const tempV = new THREE.Vector3();
const raycaster = new THREE.Raycaster();
cubes.forEach((cubeInfo) => {
const {cube, elem} = cubeInfo;
cube.updateWorldMatrix(true, false);
cube.getWorldPosition(tempV);
tempV.project(camera);
raycaster.setFromCamera(tempV, camera);
const intersectedObjects = raycaster.intersectObjects(scene.children);
const show = intersectedObjects.length && cube === intersectedObjects[0].object;
elem.style.display = show ? "" : "none";
if (show) {
const x = (tempV.x * .5 + .5) * canvas.clientWidth;
const y = (tempV.y * -.5 + .5) * canvas.clientHeight;
elem.style.transform = `translate(-50%, -50%) translate(${x}px,${y}px)`;
}
});
Vector3.project(camera) to turn a world position into normalized screen coordinates for CSS placement.zIndex (with a large multiplier) so overlapping labels stack in the correct front-to-back order.