如何在Vue 3中使用JavaScript实现Three.js场景入门示例
在Vue.js 3(JavaScript)中实现Three.js官方入门场景
实现步骤
1. 安装Three.js依赖
在Vue项目根目录执行命令:
npm install three # 或使用yarn yarn add three
2. 创建Three.js场景组件
新建src/components/ThreeScene.vue文件,写入以下代码:
<template> <div ref="sceneContainer" class="three-scene-container"></div> </template> <script> import * as THREE from 'three' export default { name: 'ThreeScene', data() { return { scene: null, camera: null, renderer: null, cube: null, animationId: null } }, mounted() { this.initScene() this.initAnimation() window.addEventListener('resize', this.handleResize) }, beforeUnmount() { window.removeEventListener('resize', this.handleResize) cancelAnimationFrame(this.animationId) this.renderer.dispose() this.scene.traverse((obj) => { if (obj.geometry) obj.geometry.dispose() if (obj.material) obj.material.dispose() }) }, methods: { initScene() { const container = this.$refs.sceneContainer if (!container) return // 初始化场景 this.scene = new THREE.Scene() // 创建透视相机 const aspectRatio = container.clientWidth / container.clientHeight this.camera = new THREE.PerspectiveCamera(75, aspectRatio, 0.1, 1000) this.camera.position.z = 5 // 创建WebGL渲染器并挂载到容器 this.renderer = new THREE.WebGLRenderer({ antialias: true }) this.renderer.setSize(container.clientWidth, container.clientHeight) container.appendChild(this.renderer.domElement) // 创建立方体并添加到场景 const geometry = new THREE.BoxGeometry(1, 1, 1) const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 }) this.cube = new THREE.Mesh(geometry, material) this.scene.add(this.cube) }, initAnimation() { const animate = () => { this.animationId = requestAnimationFrame(animate) // 立方体旋转动画 this.cube.rotation.x += 0.01 this.cube.rotation.y += 0.01 this.renderer.render(this.scene, this.camera) } animate() }, handleResize() { const container = this.$refs.sceneContainer if (!container) return // 窗口大小变化时更新相机和渲染器 const aspectRatio = container.clientWidth / container.clientHeight this.camera.aspect = aspectRatio this.camera.updateProjectionMatrix() this.renderer.setSize(container.clientWidth, container.clientHeight) } } } </script> <style scoped> .three-scene-container { width: 100vw; height: 100vh; margin: 0; overflow: hidden; } </style>
3. 在主应用中引入组件
修改src/App.vue文件,引入并使用上述组件:
<template> <div id="app"> <ThreeScene /> </div> </template> <script> import ThreeScene from './components/ThreeScene.vue' export default { name: 'App', components: { ThreeScene } } </script> <style> #app { margin: 0; padding: 0; } </style>
核心细节说明
- DOM挂载时机:选择在
mounted钩子中初始化Three.js逻辑,确保组件DOM已渲染完成,能正确获取到挂载容器。 - 内存泄漏防护:在组件销毁前(
beforeUnmount)清理事件监听、取消动画帧,并释放Three.js的几何体、材质、渲染器等资源。 - 窗口适配处理:监听窗口
resize事件,动态更新相机宽高比和渲染器尺寸,保证场景在窗口缩放时正常显示。 - 组件化设计:将Three.js场景逻辑封装为独立组件,提升代码复用性和可维护性。
内容的提问来源于stack exchange,提问作者three.vue.noob
相关产品推荐
相关产品推荐

