20232.9.12今天我学习了如何使用vue2+three制作一个3d图形,效果:
首先安装:
npm install three
相关代码:
<!--3d基础版,实现单个3d图形-->
<template>
<div>
<div id="content"/>
</div>
</template>
<script>
import * as THREE from 'three'
export default {
data() {
return {
scene: null,//场景
camera: null,//照相机
renderer: null,//渲染器
mesh: null,//物体
light: null,//灯光
num: 0,//增加物体
}
},
mounted() {
this.init()
},
methods: {
init() {
// 创建场景
this.createScene()
// 创建照相机
this.createCamera()
// 创建渲染器
this.createRenderer()
// 创建灯光
this.createLight()
// 创建物体
this.createMesh()
// 触发
this.render()
this.animation()
},
// 创建场景
createScene() {
this.scene = new THREE.Scene()
},
// 创建照相机
createCamera() {
this.camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 1000)
this.camera.position.set(200, 200, 200)
this.camera.lookAt(this.scene.position)
},
// 创建渲染器
createRenderer() {
this.renderer = new THREE.WebGLRenderer()
this.renderer.setSize(window.innerWidth, window.innerHeight)
this.renderer.setClearColor(new THREE.Color(0xffffff))
document.getElementById('content').appendChild(this.renderer.domElement)
},
// 创建灯光
createLight() {
this.light = new THREE.DirectionalLight({
color: 'red'
})
this.light.position.set(100, 100, 100)
this.scene.add(this.light)
},
// 创建物体
createMesh() {
const geometry = new THREE.BoxGeometry(30, 30, 30)
const material = new THREE.MeshLambertMaterial({
color: 0x0000ff
})
this.mesh = new THREE.Mesh(geometry, material)
this.scene.add(this.mesh)
this.render()
},
//触发
render() {
this.renderer.render(this.scene, this.camera)
},
animation() {
let time = new Date() * 0.001;
// 对物体旋转
// this.mesh.position.set(100 * Math.cos(time), 100 * Math.sin(time), 0)
// 对照相机旋转
// this.camera.position.set(100 * Math.cos(time), 100 * Math.sin(time), 0)
// this.camera.lookAt(this.scene.position)
this.render()
requestAnimationFrame(this.animation)
}
}
}
</script>