vue2项目中使用three.js创建一个旋转的正方体
时间: 2023-11-26 21:03:26 浏览: 103
vue-three.rar基于Three.js
1. 安装three.js
```
npm install three
```
2. 创建一个Vue组件
```
<template>
<div ref="container"></div>
</template>
<script>
import * as THREE from 'three'
export default {
name: 'ThreeCube',
mounted() {
this.init()
},
methods: {
init() {
// 创建场景
const scene = new THREE.Scene()
// 创建摄像机
const camera = new THREE.PerspectiveCamera(75, this.$refs.container.clientWidth / this.$refs.container.clientHeight, 0.1, 1000)
camera.position.z = 5
// 创建渲染器
const renderer = new THREE.WebGLRenderer()
renderer.setSize(this.$refs.container.clientWidth, this.$refs.container.clientHeight)
this.$refs.container.appendChild(renderer.domElement)
// 创建正方体
const geometry = new THREE.BoxGeometry(1, 1, 1)
const material = new THREE.MeshBasicMaterial({ color: 0xcccccc })
const cube = new THREE.Mesh(geometry, material)
scene.add(cube)
// 渲染场景
function animate() {
requestAnimationFrame(animate)
cube.rotation.x += 0.01
cube.rotation.y += 0.01
renderer.render(scene, camera)
}
animate()
}
}
}
</script>
<style scoped>
div {
height: 100%;
width: 100%;
}
</style>
```
3. 在Vue页面中引入该组件并使用
```
<template>
<div>
<three-cube />
</div>
</template>
<script>
import ThreeCube from './components/ThreeCube.vue'
export default {
name: 'App',
components: {
ThreeCube
}
}
</script>
```
4. 运行项目,可以看到旋转的正方体。
阅读全文