three.js基础案例day12——多平面切割

其实今天的案例和第九天的差不多,都是有关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>

  • 7
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值