import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { CSS2DRenderer, CSS2DObject } from 'three/examples/jsm/renderers/CSS2DRenderer.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();
// 创建一个立方体
let geometry = new THREE.BoxGeometry(0.2, 0.2, 0.2);
mesh = new THREE.Mesh(geometry, new THREE.MeshNormalMaterial());
scene.add(mesh);
// 创建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);
// 创建2D标签对象
let label = document.createElement('div');
label.style.color = 'white';
label.innerHTML = 'Hello Three.js!';
let labelObject = new CSS2DObject(label);
labelObject.position.set(0.5, 0.5, 0);
scene.add(labelObject);
renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);
document.body.appendChild(renderer.domElement);
// 添加轨道控制器
controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
// 监听窗口大小变化
window.addEventListener('resize', onWindowResize, false);
}
function animate() {
requestAnimationFrame(animate);
render();
}
function render() {
controls.update();
mesh.rotation.x += 0.01;
mesh.rotation.y += 0.005;
renderer.render(scene, camera);
labelRenderer.render(scene, camera);
}
function onWindowResize() {
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.inn
评论已关闭