其实今天的案例和第九天的差不多,都是有关clipping相关的。是多个不同颜色的小球组成。具体效果如下:
首先需要搭建基础环境,场景、相机、渲染器和控制器,不清楚的请查看three.js基础案例day01.
今天这个案例比较简单就直接贴全部代码了,其实主要是创建多个从小到大的球体,创建3条线来进行剪切这个球体,进而得到上面的效果。
注:若球体的材质设置了clippingPlanes属性,但是球体并没有被剪开,看下renderer的localClippingEnabled有没有设置为true。
全部代码:
<template>
<div id="threeId" ref="elementRef"></div>
</template>
<script setup>
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { ref, onMounted } from 'vue'
let width, height, scene, camera, renderer, controls
const elementRef = ref(null)
const clipPlanes = [
new THREE.Plane( new THREE.Vector3(1, 0, 0), 0 ),
new THREE.Plane( new THREE.Vector3(0, -1, 0), 0 ),
new THREE.Plane( new THREE.Vector3(0, 0, -1), 0 ),
]
onMounted(() => {
const element = elementRef.value
width = element.offsetWidth
height = element.offsetHeight
initScene()
initMeshes()
render()
})
function initScene() {
// 初始化场景: 创建场景,相机,物体,渲染器
scene = new THREE.Scene()
scene.background = new THREE.Color(0xcccccc)
console.log('three', THREE)
camera = new THREE.PerspectiveCamera(60, width / height, 1, 1000)
camera.position.set(5, 5, 5)
scene.add(camera)
// const axesHelper = new THREE.AxesHelper(40)
// scene.add(axesHelper)
const light = new THREE.HemisphereLight(0xffffff, 0x080808)
light.position.set(-1.25, 1, 1.25)
scene.add(light)
renderer = new THREE.WebGLRenderer()
renderer.setSize(width, height)
elementRef.value.appendChild(renderer.domElement)
renderer.localClippingEnabled = true
controls = new OrbitControls(camera, renderer.domElement)
controls.update()
}
function initMeshes() {
const group = new THREE.Group()
for (let i = 1; i<= 30;i += 2) {
const geometry = new THREE.SphereGeometry( i / 30, 48, 24 )
const material = new THREE.MeshLambertMaterial({
color:new THREE.Color().setHSL(Math.random(), 0.5, 0.5),
side: THREE.DoubleSide,
clippingPlanes: clipPlanes,
clipIntersection:true,
})
const mesh = new THREE.Mesh(geometry, material)
group.add(mesh)
}
scene.add(group)
}
function render() {
requestAnimationFrame(render)
controls.update()
renderer.render(scene, camera)
}
</script>
<style lang="scss" scoped>
#threeId {
width: 100%;
height: 100%;
}
</style>