在Vue2项目中使用Three.js并在3D模型上方显示信息框,可以使用CSS3DSprite
创建一个精灵模型来代表信息框。以下是一个简化的例子:
- 安装Three.js:
npm install three
- 在Vue组件中创建Three.js场景,并添加3D模型和CSS3DSprite信息框:
<template>
<div ref="threeContainer"></div>
</template>
<script>
import * as THREE from 'three';
import { CSS3DRenderer, CSS3DSprite } from 'three/examples/jsm/renderers/CSS3DRenderer.js';
export default {
name: 'ThreeModelWithLabel',
mounted() {
this.initThree();
this.add3DModel();
this.addLabelSprite();
this.animate();
},
methods: {
initThree() {
const width = this.$refs.threeContainer.clientWidth;
const height = this.$refs.threeContainer.clientHeight;
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, width / height, 0.1, 1000);
this.renderer = new THREE.WebGLRenderer();
this.renderer.setSize(width, height);
this.$refs.threeContainer.appendChild(this.renderer.domElement);
this.cssRenderer = new CSS3DRenderer();
this.cssRenderer.setSize(width, height);
this.cssRenderer.domElement.style.position = 'absolute';
this.cssRenderer.domElement.style.top = 0;
this.$refs.threeContainer.appendChild(this.cssRenderer.domElement);
this.camera.position.z = 5;
},
add3DModel() {
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
this.cube = new THREE.Mesh(geometry, material);
this.scene.add(this.cube);
},
addLabelSprite() {
const sprite = new CSS3DSprite(document.createElement('div'));
sprite.scale.set(0.2, 0.2, 0.2);
sprite.position.set(0, 1, 0); // 在模型上方1单位处创建精灵模型
sprite.material.transparent = true;
this.scene.add(sprite);
this.labelSprite = sprite;
},
animate() {
requestAnimationFrame(this.animate);
this.renderer.render(this.scene, this.camera);
this.cssRenderer.render(this.scene, this.camera);
// 示例:旋转模型和标签位置
this.cube.rotation.x += 0.01;
this.cube.rotation.y += 0.01;
this.labelSprite.rotation.x += 0.01;
this.labelSprite.rotat