three.js官方CSS2DRender案例学习
import * as THREE from 'three';
import { CSS2DRenderer, CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer.js';
let scene, camera, renderer, labelRenderer, mesh;
function init() {
scene = new THREE.Scene();
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
camera.position.z = 1;
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 创建CSS2DRenderer
labelRenderer = new CSS2DRenderer();
labelRenderer.setSize(window.innerWidth, window.innerHeight);
labelRenderer.domElement.style.position = 'absolute';
labelRenderer.domElement.style.top = 0;
document.body.appendChild(labelRenderer.domElement);
// 创建3D对象
let geometry = new THREE.PlaneGeometry(0.5, 0.5);
let material = new THREE.MeshBasicMaterial({ color: 0x00ff00, transparent: true });
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
// 创建CSS2DObject
let label = document.createElement('div');
label.style.color = 'red';
label.textContent = 'Hello, CSS2D!\n3D object!';
let labelObject = new CSS2DObject(label);
labelObject.position.set(0, 0, 0);
scene.add(labelObject);
// 监听窗口大小变化
window.addEventListener('resize', onWindowResize, false);
animate();
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
labelRenderer.setSize(window.innerWidth, window.innerHeight);
}
function animate() {
requestAnimationFrame(animate);
renderer.render(scene, camera);
labelRenderer.render(scene, camera);
}
init();
这段代码初始化了Three.js场景,并使用CSS2DRenderer渲染了一个2D标签,它会随着3D对象一起旋转。这个例子简单地展示了如何将HTML元素与3D场景中的对象相关联,这在创建交互式数据可视化时非常有用。
评论已关闭