Threejs之场景标注标签信息CSS2DRenderer
CSS2DRenderer是Three.js中用于渲染2D标签的一个工具,它允许你在3D场景中添加2D CSS样式的标签。以下是一个简单的例子,展示如何使用CSS2DRenderer标注Three.js场景中的一个物体:
import * as THREE from 'three';
import { CSS2DRenderer, CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer.js';
// 创建场景、摄像机和渲染器
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建CSS2DRenderer
const labelRenderer = new CSS2DRenderer();
labelRenderer.setSize(window.innerWidth, window.innerHeight);
labelRenderer.domElement.style.position = 'absolute';
labelRenderer.domElement.style.top = 0;
document.body.appendChild(labelRenderer.domElement);
// 创建一个物体
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// 创建CSS2DObject标签
const label = document.createElement('div');
label.style.color = 'white';
label.innerHTML = 'Hello, Three.js!';
const labelObject = new CSS2DObject(label);
labelObject.position.set(0, 1, 0); // 放置在物体正上方
scene.add(labelObject);
camera.position.z = 5;
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
labelRenderer.render(scene, camera);
}
animate();
这段代码创建了一个Three.js场景,添加了一个立方体和一个2D标签,标签会随着立方体的移动而移动。CSS2DRenderer用于渲染HTML元素,使得我们可以给物体添加复杂的CSS样式。这是一个Three.js中实现2D标注的简单例子。
评论已关闭