前言:
three.js基本使用没问下,下面进入自定义图形
效果展示
实现
使用BufferGeometry()自定义
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as THREE from 'three'
// 导入轨道控制器
import { OrbitControls } from 'three/addons/controls/OrbitControls.js'const container = ref<HTMLDivElement>()// 创建场景
const scene = new THREE.Scene()// 创建相机对象
const camera = new THREE.PerspectiveCamera(75,window.innerWidth / window.innerHeight,0.1,1000
)
// 设置相机位置
camera.position.set(0, 0, 10)
scene.add(camera)// 添加物体
// 创建几何体
for (let i = 0; i < 100; i++) {const geometry = new THREE.BufferGeometry()const positionArray = new Float32Array(9)for (let j = 0; j < 9; j++) {positionArray[j] = Math.random() * 10 - 5}geometry.setAttribute('position', new THREE.BufferAttribute(positionArray, 3))const color = new THREE.Color(Math.random(), Math.random(), Math.random())const material = new THREE.MeshBasicMaterial({color,transparent: true,opacity: 0.5 // 透明度})// 根据几何体和材质创建物体const cube = new THREE.Mesh(geometry, material)// 将几何体添加到场景中scene.add(cube)
}// 初始化渲染器
const renderer = new THREE.WebGLRenderer()
renderer.setClearColor(new THREE.Color(0xeeeeee))
// 设置three.js渲染区域的尺寸(像素px)
renderer.setSize(window.innerWidth, window.innerHeight)// 创建控制器
const controls = new OrbitControls(camera, renderer.domElement)
// 设置阻尼,使得动画更逼真,调用update()
controls.enableDamping = true// 坐标轴
const axesHelper = new THREE.AxesHelper(10)
scene.add(axesHelper)
// 设置时钟
// const clock = new THREE.Clock()// 监听事件,双击暂停
window.addEventListener('dblclick', () => {// 全屏if (document.fullscreenElement === null) {renderer.domElement.requestFullscreen()} else {document.exitFullscreen()}
})
const render = () => {controls.update()renderer.render(scene, camera) // 执行渲染操作requestAnimationFrame(render)
}
// 监听页面变化
window.addEventListener('resize', () => {// 更新摄像头camera.aspect = window.innerWidth / window.innerHeight// 更新摄像机的投影矩阵camera.updateProjectionMatrix()// 更新渲染器renderer.setSize(window.innerWidth, window.innerHeight)// 设置渲染器的像素比renderer.setPixelRatio(window.devicePixelRatio)
})
onMounted(() => {container.value?.appendChild(renderer.domElement)render()
})
</script><template><div ref="container" class="container"></div>
</template>
<style scoped lang="scss">
.container {height: 100%;width: 100%;
}
</style>