3D组件设计
three.js
<-template->
<-div ref="container" class="three-container"-><-/div->
<-/template->
<-script setup->
let renderer;
const container = ref(null);
const showCube = ref(true);
let cube = null;
// 初始化3D场景的函数
const initThree = () =-> {
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xffffff);
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
renderer.setSize(window.innerWidth, window.innerHeight);
container.value.appendChild(renderer.domElement);
// 添加光源
const ambientLight = new THREE.AmbientLight(0x404040);
const directionalLight = new THREE.DirectionalLight(0xffffff, 0.5);
scene.add(ambientLight);
scene.add(directionalLight);
camera.position.z = 5;
// 创建立方体
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x44aa88 });
cube = new THREE.Mesh(geometry, material);
scene.add(cube);
// 动画循环
const animate = () =-> {
requestAnimationFrame(animate);
// 根据状态设置立方体可见性
cube.visible = showCube.value;
// 旋转立方体
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
};
animate();
};
const toggleCube = () =-> {
showCube.value = !showCube.value;
};
const dispose = () =-> {
if (renderer) {
renderer.dispose();
}
};
onMounted(() =-> {
initThree();
});
onBeforeUnmount(() =-> {
dispose();
});
<-/script->
<-style scoped->
.three-container {
background-color:var(--background);
width: 300px;
height: 300px;
overflow: hidden;
display: flex;
justify-content: center;
align-items: center;
position: relative;
resize: both;
min-width: 200px;
min-height: 200px;
cursor: pointer;
margin-bottom: 26px;
}
<-/style->
gif图像
<-img src="@/assets/heartomg.gif" class="three-container"/->