import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
import { CSS3DRenderer, CSS3DObject } from 'three/examples/jsm/renderers/CSS3DRenderer.js';
let camera, scene, renderer, labelRenderer, controls;
let mixers = [];
init();
animate();
function init() {
// 初始化camera和scene
camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.set(0, 10, 50);
scene = new THREE.Scene();
// 添加灯光
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
scene.add(ambientLight);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
directionalLight.position.set(1, 1, 1);
scene.add(directionalLight);
// 创建CSS3DRenderer
labelRenderer = new CSS3DRenderer();
labelRenderer.setSize(window.innerWidth, window.innerHeight);
labelRenderer.domElement.style.position = 'absolute';
labelRenderer.domElement.style.top = 0;
document.body.appendChild(labelRenderer.domElement);
// 创建div元素作为标签
function createLabel(text) {
const label = document.createElement('div');
label.textContent = text;
label.style.color = 'white';
label.style.fontSize = '12px';
const labelObject = new CSS3DObject(label);
labelObject.position.set(0, 0, 0);
return labelObject;
}
// 加载模型
const loader = new GLTFLoader();
loader.load('models/scene.gltf', (gltf) => {
gltf.scene.scale.set(0.01, 0.01, 0.01);
gltf.scene.rotation.set(Math.PI / 2, 0, 0);
scene.add(gltf.scene);
// 添加标签到CSS3DObject
const label = createLabel('电影标签');
label.position.set(0, 5, 0);
scene.add(label);
// 添加动画
mixers.push(...gltf.animations.map((clip, i) => {
const action = mixer.clipAction(clip);
action.play();
return mixer;
}));
});
// 初始化控制器
controls = new OrbitControls(camera, labelRenderer.domElement);
controls.enableDamping = true;
// 渲染函数
function animate() {
requestAnimationFrame(animate);
renderer && renderer.render(scene, camera);
labelRenderer && labelRenderer.render(scene, camera);
mixers.forEach(mixer => mixer.update(cloc