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>