Three.js:如何设置裁剪平面实现父物体范围内子物体裁剪
使用Three.js裁剪平面实现子物体仅在父物体范围内显示
嘿,这个需求其实用Three.js的**裁剪平面(Clipping Planes)**就能完美解决!核心思路就是给子物体的材质添加一组刚好贴合父物体边界的裁剪平面,让超出父物体范围的部分直接被裁掉。下面是具体的实现步骤和完整代码:
实现步骤
- 先确定父物体
baseObject的边界范围,根据它的几何尺寸和位置创建对应的裁剪平面 - 给子物体的材质启用裁剪功能,把定义好的裁剪平面赋值给材质的
clippingPlanes属性 - 注意裁剪平面的法线方向:要确保法线朝向父物体内部,这样才能正确裁剪外部区域
完整代码示例
// 初始化场景、相机、渲染器 const scene = new THREE.Scene(); const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000); const renderer = new THREE.WebGLRenderer(); renderer.setSize(window.innerWidth, window.innerHeight); document.body.appendChild(renderer.domElement); // 创建父物体baseObject(100x100的黄色平面) const baseGeometry = new THREE.PlaneGeometry(100, 100); const baseMaterial = new THREE.MeshBasicMaterial({ color: 0xffff00, side: THREE.DoubleSide }); const baseObject = new THREE.Mesh(baseGeometry, baseMaterial); scene.add(baseObject); // 定义裁剪平面:贴合baseObject的上下左右边界 // 计算baseObject的半宽半高 const halfWidth = baseGeometry.parameters.width / 2; const halfHeight = baseGeometry.parameters.height / 2; // 四个裁剪平面:左、右、上、下 const clippingPlanes = [ // 左平面:x = -halfWidth,法线朝右(x正方向) new THREE.Plane(new THREE.Vector3(1, 0, 0), halfWidth), // 右平面:x = halfWidth,法线朝左(x负方向) new THREE.Plane(new THREE.Vector3(-1, 0, 0), halfWidth), // 上平面:y = halfHeight,法线朝下(y负方向) new THREE.Plane(new THREE.Vector3(0, -1, 0), halfHeight), // 下平面:y = -halfHeight,法线朝上(y正方向) new THREE.Plane(new THREE.Vector3(0, 1, 0), halfHeight), ]; // 创建子物体childObject(200x200的蓝色平面,比父物体大) const childGeometry = new THREE.PlaneGeometry(200, 200); const childMaterial = new THREE.MeshBasicMaterial({ color: 0x0000ff, side: THREE.DoubleSide, // 启用裁剪并设置裁剪平面 clippingPlanes: clippingPlanes, // 如果需要裁剪阴影,开启这个属性 clipShadows: true, // clipIntersection设为false:显示所有裁剪平面内部的区域(默认值) // 如果设为true,会显示裁剪平面外部的区域,这里不要开 clipIntersection: false }); const childObject = new THREE.Mesh(childGeometry, childMaterial); // 把子物体挂载到父物体下 baseObject.add(childObject); // 设置相机位置 camera.position.z = 150; // 渲染循环 function animate() { requestAnimationFrame(animate); renderer.render(scene, camera); } animate();
关键注意事项
- 裁剪平面的
THREE.Plane构造函数参数:第一个是法线向量,第二个是平面到原点的距离(沿法线方向) - 如果父物体有旋转或位移,你需要实时更新裁剪平面的位置和方向,确保始终贴合父物体的边界
- 不是所有材质都支持裁剪平面,比如
RawShaderMaterial需要自己实现裁剪逻辑,但基础材质(如MeshBasicMaterial、MeshStandardMaterial)都原生支持
内容的提问来源于stack exchange,提问作者BAR
相关产品推荐
相关产品推荐

