可以参考下面代码,粘贴上去就有了~
<template>
<div class="container">
<h1>初步构造出辅助线</h1>
<canvas ref="mainCanvas"></canvas>
</div>
</template>
<script>
import * as THREE from 'three'
const OrbitControls = require('three-orbit-controls')(THREE)
export default {
props: {},
data() {
return {
// 公共项目1
scene: new THREE.Scene(),
camera: null,
renderer: new THREE.WebGLRenderer(), // 渲染器
directionalLight: new THREE.DirectionalLight(0xff0000, 1.0, 0),
controls: OrbitControls,
cars: [],
width: '',
height: '',
config: {
isMobile: false,
background: 0x282828
}
// 公共项目2
}
},
computed: {},
watch: {},
created() {},
mounted() {
this.width = window.innerWidth
this.height = window.innerHeight
this.scene = new THREE.Scene()
this.camera = new THREE.PerspectiveCamera(
45, // 视野角fov
this.width / this.height,
1,
5000
)
this.camera.position.set(330, 330, 330)
this.camera.lookAt(this.scene.position)
this.canvas = this.$refs.mainCanvas
this.renderer = new THREE.WebGLRenderer({
antialias: true, // antialias:true/false是否开启反锯齿
canvas: this.canvas
})
this.renderer.setSize(this.width, this.height)
this.renderer.setClearColor(this.config.background)
this.renderer.shadowMap.enabled = true // 輔助線
this.renderer.shadowMap.type = THREE.PCFSoftShadowMap // 柔化边缘的软阴影映射
this.checkUserAgent() // 检测浏览器类型
this.bulidAuxSystem() // 构建辅助系统
this.buildLightSystem() // 光线
this.loop()
},
methods: {
// 检测浏览器类型1
checkUserAgent() {
const n = navigator.userAgent
if (
n.match(/Android/i) ||
n.match(/webOs/i) ||
n.match(/iPhone/i) ||
n.match(/iPad/i) ||
n.match(/iPod/i) ||
n.match(/BlackBerry/i)
) {
this.config.isMobile = true
this.camera.position.set(420, 420, 420)
this.renderer.shadowMap.enabled = false // 輔助線
}
},
// 检测浏览器类型2
// 构建辅助系统1
bulidAuxSystem() {
const gridHelper = new THREE.GridHelper(320, 32)
this.scene.add(gridHelper)
this.controls = new OrbitControls(this.camera, this.renderer.domElement)
this.controls.enableDamping = true
this.controls.dampingFactor = 0.25
this.controls.rotateSpeed = 0.35
},
// 构建辅助系统2
buildLightSystem() {
console.log('是否手机', this.config.isMobile)
if (!this.config.isMobile) {
console.log('是否手机11')
this.directionalLight.position.set(300, 1000, 500)
this.directionalLight.target.position.set(0, 0, 0)
this.directionalLight.castShadow = true
const d = 300
this.directionalLight.shadow.camera = new THREE.OrthographicCamera(
-d,
d,
d,
-d,
500,
1600
)
this.directionalLight.shadow.bias = 0.0001
this.directionalLight.shadow.mapSize.width = this.directionalLight.shadow.mapSize.height = 1024
this.scene.add(this.directionalLight)
const light = new THREE.AmbientLight(0xffffff, 0.3)
this.scene.add(light)
} else {
console.log('是否手机22')
const hemisphereLight = new THREE.HemisphereLight(0xffffff, 1)
this.scene.add(hemisphereLight)
this.scene.add(new THREE.AmbientLight(0xffffff, 0.15))
}
},
loop() {
this.renderer.render(this.scene, this.camera)
requestAnimationFrame(this.loop)
}
}
}
</script>
<style scoped lang="less">
</style>