代码如下
<template>
<div style="1000px; height:800px">
<p>逃跑的圆柱体</p>
<div ref="myBody" id="canvas-frame" style="1000px; height:800px" />
</div>
</template>
<script>
import * as THREE from 'three'
import { OBJLoader, MTLLoader } from 'three-obj-mtl-loader'
import { CSS2DRenderer, CSS2DObject } from 'three-css2drender'
export default {
data() {
return {
scene: new THREE.Scene(), // 场景
camera: new THREE.PerspectiveCamera(
45,
window.innerWidth / window.innerHeight,
1,
10000
), // 透视相机
renderer: new THREE.WebGLRenderer(), // 渲染器
geometry: new THREE.Geometry(), // 设置物体
material: new THREE.LineBasicMaterial({ vertexColors: true }), // 设置材料
cube: {}, // 合起来
// 开始设置线条
light: new THREE.DirectionalLight(0xff0000, 1.0, 0)
}
},
mounted() {
this.threeStart()
},
methods: {
initThree() {
const width = this.$refs.myBody.clientWidth
const height = this.$refs.myBody.clientHeight
this.renderer = new THREE.WebGLRenderer({ antialias: true })
this.renderer.setSize(width, height)
this.$refs.myBody.appendChild(this.renderer.domElement)
this.renderer.setClearColor(0xffffff, 1.0)
},
initCamera() {
this.camera = new THREE.PerspectiveCamera(130, 1.5, 1, 10000)
this.camera.position.x = 0
this.camera.position.y = 0
this.camera.position.z = 600
this.camera.up.x = 0
this.camera.up.y = 1
this.camera.up.z = 0
this.camera.lookAt(0, 0, 0)
},
initScene() {
this.scene = new THREE.Scene()
},
initLight() {
var light = new THREE.AmbientLight(0xffffff)
light.position.set(100, 100, 200)
this.scene.add(light)
var light1 = new THREE.PointLight(0x00ff00)
light1.position.set(0, 0, 300)
this.scene.add(light1)
},
initObject() {
var geometry = new THREE.CylinderGeometry(80, 100, 400)
var material = new THREE.MeshLambertMaterial({ color: 0x32d3eb })
var mesh = new THREE.Mesh(geometry, material)
this.scene.add(mesh)
},
animation() {
this.camera.position.x = this.camera.position.x += 3
this.camera.position.y = this.camera.position.y += 3
this.renderer.render(this.scene, this.camera)
requestAnimationFrame(this.animation)
},
threeStart() {
this.initThree()
this.initCamera()
this.initScene()
this.initLight()
this.initObject()
this.animation()
},
consoleObj() {
console.log(THREE.REVISION)
console.log(OBJLoader)
console.log(MTLLoader)
console.log(CSS2DRenderer)
console.log(CSS2DObject)
}
}
}
</script>
<style lang="less" scoped>
#canvas_frame {
border: none;
cursor: pointer;
100%;
height: 600px;
background-color: #eeeeee;
}
</style>