Threejs进阶之一:基于vite+vue3+threejs构建三维场景
// 安装所需依赖
npm install three @types/three vite vue-threejs
// 项目结构
- public/
- src/
- App.vue
- main.js
- index.html
- components/
- ThreeJsComponent.vue
// App.vue
<template>
<div id="app">
<ThreeJsComponent />
</div>
</template>
<script>
import ThreeJsComponent from './components/ThreeJsComponent.vue';
export default {
name: 'App',
components: {
ThreeJsComponent
}
}
</script>
// main.js
import { createApp } from 'vue';
import App from './App.vue';
createApp(App).mount('#app');
// ThreeJsComponent.vue
<template>
<div ref="threeJsContainer" class="three-js-container"></div>
</template>
<script>
import * as THREE from 'three';
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
export default {
name: 'ThreeJsComponent',
mounted() {
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const renderer = new THREE.WebGLRenderer();
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
camera.position.z = 5;
this.$refs.threeJsContainer.appendChild(renderer.domElement);
function animate() {
requestAnimationFrame(animate);
cube.rotation.x += 0.01;
cube.rotation.y += 0.01;
renderer.render(scene, camera);
}
renderer.setSize(window.innerWidth, window.innerHeight);
animate();
const controls = new OrbitControls(camera, renderer.domElement);
controls.enableDamping = true;
controls.update();
}
}
</script>
<style>
.three-js-container {
width: 100vw;
height: 100vh;
overflow: hidden;
}
</style>
这段代码展示了如何在Vue 3应用中使用Three.js创建一个基本的3D场景。它包括了一个立方体的创建、相机的设置、渲染器的初始化、动画的添加以及轨道控制器的使用。这个例子为开发者提供了一个简明的Three.js和Vue 3集成的示例。
评论已关闭