在Three.js中使用CSS3DRenderer和CSS3DSprite实现模型标签文字+指示线
import * as THREE from 'three';
import { CSS3DRenderer, CSS3DSprite } from 'three/examples/jsm/renderers/CSS3DRenderer.js';
// 创建场景、摄像机和渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new CSS3DRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
document.body.appendChild(renderer.css3DObject.element);
// 创建模型标签文字和指示线的函数
function createLabelAndLine(text, position) {
// 创建CSS3DSprite作为文字
const label = new CSS3DSprite(document.createElement('div'));
label.element.style.cssText = `
font-size: 12px;
color: #ffffff;
padding: 2px;
border: 1px solid #000000;
border-radius: 4px;
background-color: #000000;
text-align: center;
`;
label.element.textContent = text;
label.position.set(position.x, position.y, position.z);
scene.add(label);
// 创建指示线
const geometry = new THREE.Geometry();
geometry.vertices.push(
new THREE.Vector3(position.x, position.y, position.z),
new THREE.Vector3(position.x + 1, position.y, position.z)
);
const lineMaterial = new THREE.LineBasicMaterial({ color: 0xffffff });
const line = new THREE.Line(geometry, lineMaterial);
scene.add(line);
}
// 创建模型(此处省略)
// ...
// 创建模型标签文字和指示线
createLabelAndLine('Model Label', new THREE.Vector3(0, 0, 0));
// 渲染循环
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
}
animate();
这段代码展示了如何在Three.js中结合CSS3DRenderer和CSS3DSprite来创建模型标签文字和指示线。首先,创建了一个场景、摄像机和CSS3DRenderer渲染器。然后定义了一个函数createLabelAndLine
来创建文字和线,最后在场景中添加了模型和相应的标签文字及指示线。最后,进入了一个简单的渲染循环。
评论已关闭