Threejs进阶之七:使用CSS3DRenderer渲染HTML标签
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { CSS3DRenderer, CSS3DObject } from 'three/examples/jsm/renderers/CSS3DRenderer.js';
let camera, scene, renderer, labelRenderer, controls;
let mesh;
init();
animate();
function init() {
camera = new THREE.PerspectiveCamera(70, window.innerWidth / window.innerHeight, 0.01, 10);
camera.position.set(0.5, 0.5, 0.5);
scene = new THREE.Scene();
mesh = new THREE.Mesh(new THREE.BoxGeometry(1, 1, 1));
scene.add(mesh);
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
labelRenderer = new CSS3DRenderer();
labelRenderer.setSize(window.innerWidth, window.innerHeight);
labelRenderer.domElement.style.position = 'absolute';
labelRenderer.domElement.style.top = 0;
document.body.appendChild(labelRenderer.domElement);
controls = new OrbitControls(camera, labelRenderer.domElement);
// 创建CSS3DObject并关联HTML元素
const label = new CSS3DObject(document.createElement('div'));
label.element.style.width = '100px';
label.element.style.height = '100px';
label.element.style.background = 'red';
label.position.set(0.5, 0.5, 0);
scene.add(label);
// 创建一个新的CSS3DObject并关联另一个HTML元素
const anotherLabel = new CSS3DObject(document.createElement('div'));
anotherLabel.element.style.width = '50px';
anotherLabel.element.style.height = '50px';
anotherLabel.element.style.background = 'blue';
anotherLabel.position.set(-0.5, 0.5, 0);
scene.add(anotherLabel);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.005;
controls.update();
renderer.render(scene, camera);
labelRenderer.render(scene, camera);
}
这段代码初始化了Three.js场景,包括相机、场景、灯光、物体以及渲染器。使用CSS3DRenderer渲染了一个红色的HTML DIV标签和一个蓝色的HTML DIV标签,并且它们会随着物体旋转而旋转。这是一个Three.js中CSS3DRenderer的基本使用案例。
评论已关闭