Three.js是一个跨浏览器的脚本,使用JavaScript函数库或API来在网页浏览器中创建和展示动画的三维计算机图形。Three.js使用WebGL。源代码托管在GitHub。
下面介绍在Vue.js中集成three.js的步骤。
- 安装vue-cli脚手架
- 安装three.js
1
npm install --save three
- 编写使用three.js创建3D场景的Vuejs组件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59<template>
<div id="container"></div>
</template>
<script>
import * as Three from 'three'
export default {
name: 'Home',
data () {
return {
camera: null,
scene: null,
renderer: null,
mesh: null
}
},
methods: {
init: function () {
var container = document.getElementById('container')
this.camera = new Three.PerspectiveCamera(70, container.clientWidth / container.clientHeight, 0.01, 10)
this.camera.position.z = 1
this.scene = new Three.Scene()
var geometry = new Three.BoxGeometry(0.2, 0.2, 0.2)
var material = new Three.MeshNormalMaterial()
this.mesh = new Three.Mesh(geometry, material)
this.scene.add(this.mesh)
this.renderer = new Three.WebGLRenderer({ antialias: true })
this.renderer.setSize(container.clientWidth, container.clientHeight)
container.appendChild(this.renderer.domElement)
},
animate: function () {
requestAnimationFrame(this.animate)
this.mesh.rotation.x += 0.01
this.mesh.rotation.y += 0.02
this.renderer.render(this.scene, this.camera)
}
},
mounted () {
this.init()
this.animate()
}
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
#container {
width: 100%;
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
</style>
参考链接
- Three.js, by Wikipedia
- Import and use three.js library in vue component, by Stackoverlflow