Article directory
Detailed Vue 2 + Three.js environment construction process:
1. Install Node.js and npm
If you have not installed Node.js and npm, please go to the Node.js official website to download and install it.
2. Use Vue CLI to create a new Vue project
Vue CLI is a command line tool officially provided by Vue.js, which can be used to quickly create and manage Vue projects.
To create a new Vue project, open a command line terminal and run the following command:
vue create my-project
where my-project
is your project name, you can customize it if needed.
3. Install Three.js as a project dependency
Go into the project directory and run the following command to install Three.js:
cd my-project
npm install three
4. Create a new Vue component for Three.js scenarios
src/components
Create a file called in the Vue project's directory ThreeScene.vue
and populate it with the following code:
<template>
<div ref="container"></div>
</template>
<script>
import * as THREE from 'three';
export default {
mounted() {
// 创建Three.js场景
this.scene = new THREE.Scene();
this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer.setSize(window.innerWidth, window.innerHeight);
this.refs.container.appendChild(this.renderer.domElement);
// 向场景添加对象
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
this.scene.add(cube);
// 渲染场景
this.animate();
},
methods: {
animate() {
requestAnimationFrame(this.animate);
this.renderer.render(this.scene, this.camera);
},
},
};
</script>
This code creates a simple Three.js scene containing a green cube. In mounted
the lifecycle hook, it creates the Three.js scene and renders it into the Vue component's HTML template.
5. Import the Three.js component in the Vue application and render it in the main component
Open the Vue project's src/App.vue
file and replace it with the following code:
<template>
<div id="app">
<ThreeScene />
</div>
</template>
<script>
import ThreeScene from '@/components/ThreeScene';
export default {
name: 'App',
components: {
ThreeScene,
},
};
</script>
This code imports ThreeScene
the component and renders it in the main component of the Vue application. Now when you run your Vue application you will see a green cube spinning in the center of the screen.
This is the basic setup of the Vue 2 + Three.js environment. Now you can build your own 3D scenes using the Three.js API.
Welcome to follow my original public account [GISer World]. This sharing ends here.