Clipping Box Model
Runnable Cesium example: Clipping Box Model. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.
single HTML file · CDN dependencies onlyinterface may contain Chinese labels
Source
<!--
示例:用六个裁剪平面围出一个盒子,剖开模型
要点:ClippingPlaneCollection 的平面在世界坐标里定义,每个平面保留法线正侧
依赖:CesiumJS 1.121 · jsDelivr CDN,贴图与 GLB 均由页面生成
-->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta name="robots" content="noindex,follow">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>裁剪盒剖切模型</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/cesium@1.121.0/Build/Cesium/Widgets/widgets.css">
<style>
html,body{height:100%;margin:0}
body{background:#0e1116;color:#e6e8ec;overflow:hidden;
font:13px/1.6 -apple-system,"Segoe UI","PingFang SC",sans-serif}
#c{height:100%}
.hud{position:absolute;left:12px;top:12px;z-index:5;background:rgba(23,28,35,.92);
border:1px solid #2a313b;border-radius:6px;padding:9px 12px;font-size:12px;
color:#a2a9b6;width:252px}
.hud b{color:#e6e8ec;font-weight:600}
.hud .row{margin-top:7px}
input[type=range]{width:100%}
.hud button{font:inherit;font-size:12px;padding:3px 9px;border-radius:4px;cursor:pointer;
border:1px solid #343b46;background:#1d232b;color:#cfd6e2;margin-top:8px}
.cesium-viewer-bottom .cesium-widget-credits,.cesium-viewer-animationContainer,
.cesium-viewer-timelineContainer{display:none!important}
</style>
</head>
<body>
<div id="c"></div>
<div class="hud">
<div><b>裁剪盒</b></div>
<div class="row">盒半径 <span id="hVal">110</span> 米</div>
<div class="row"><input id="half" type="range" min="40" max="140" step="5" value="110"></div>
<div class="row" id="info">六个平面同时生效</div>
<div class="row"><button id="flip">反向裁剪</button></div>
</div>
<script src="https://cdn.jsdelivr.net/npm/cesium@1.121.0/Build/Cesium/Cesium.js"></script>
<script>
(function () {
'use strict';
var viewer = new Cesium.Viewer('c', {
baseLayer: false,
baseLayerPicker: false, geocoder: false, homeButton: false,
sceneModePicker: false, navigationHelpButton: false,
animation: false, timeline: false, fullscreenButton: false,
infoBox: false, selectionIndicator: false
});
var scene = viewer.scene;
scene.globe.baseColor = Cesium.Color.fromCssColorString('#1c2733');
scene.backgroundColor = Cesium.Color.fromCssColorString('#0e1116');
scene.skyBox.show = false;
scene.sun.show = false;
scene.moon.show = false;
if (scene.skyAtmosphere) scene.skyAtmosphere.show = false;
var CENTER = Cesium.Cartesian3.fromDegrees(116.389, 39.906, 300);
var MATRIX = Cesium.Transforms.eastNorthUpToFixedFrame(CENTER);
/* ---------- 贴图:斜条纹 + 分区色块 ---------- */
function drawTexture() {
var c = document.createElement('canvas');
c.width = c.height = 256;
var ctx = c.getContext('2d');
ctx.fillStyle = '#22405c';
ctx.fillRect(0, 0, 256, 256);
ctx.strokeStyle = 'rgba(122,182,255,0.85)';
ctx.lineWidth = 10;
for (var i = -256; i < 512; i += 48) {
ctx.beginPath();
ctx.moveTo(i, 0);
ctx.lineTo(i + 256, 256);
ctx.stroke();
}
ctx.fillStyle = 'rgba(255,177,61,0.75)';
ctx.fillRect(0, 0, 256, 56);
ctx.fillStyle = 'rgba(95,208,168,0.6)';
ctx.fillRect(0, 200, 256, 56);
return c.toDataURL('image/png');
}
function pngBytes(dataUrl) {
var raw = atob(dataUrl.split(',')[1]);
var bytes = new Uint8Array(raw.length);
for (var i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
return bytes;
}
/* ---------- 带 UV 的立方体 ---------- */
function buildCube() {
var faces = [
{ n: [0, 0, 1], v: [[-1, -1, 1], [1, -1, 1], [1, 1, 1], [-1, 1, 1]] },
{ n: [0, 0, -1], v: [[1, -1, -1], [-1, -1, -1], [-1, 1, -1], [1, 1, -1]] },
{ n: [1, 0, 0], v: [[1, -1, 1], [1, -1, -1], [1, 1, -1], [1, 1, 1]] },
{ n: [-1, 0, 0], v: [[-1, -1, -1], [-1, -1, 1], [-1, 1, 1], [-1, 1, -1]] },
{ n: [0, 1, 0], v: [[-1, 1, 1], [1, 1, 1], [1, 1, -1], [-1, 1, -1]] },
{ n: [0, -1, 0], v: [[-1, -1, -1], [1, -1, -1], [1, -1, 1], [-1, -1, 1]] }
];
var uv = [[0, 1], [1, 1], [1, 0], [0, 0]];
var pos = [], nrm = [], tex = [], idx = [];
faces.forEach(function (f, fi) {
f.v.forEach(function (p, vi) {
pos.push(p[0] * 0.5, p[1] * 0.5, p[2] * 0.5);
nrm.push(f.n[0], f.n[1], f.n[2]);
tex.push(uv[vi][0], uv[vi][1]);
});
var b = fi * 4;
idx.push(b, b + 1, b + 2, b, b + 2, b + 3);
});
return {
pos: new Float32Array(pos),
nrm: new Float32Array(nrm),
uv: new Float32Array(tex),
idx: new Uint16Array(idx)
};
}
function buildGlb(gltf, chunks) {
var len = 0;
chunks.forEach(function (c) { len += c.data.byteLength; });
var bin = new Uint8Array(len);
var offset = 0;
gltf.bufferViews = chunks.map(function (c) {
var view = { buffer: 0, byteOffset: offset, byteLength: c.data.byteLength };
if (c.target) view.target = c.target;
bin.set(new Uint8Array(c.data.buffer, c.data.byteOffset, c.data.byteLength), offset);
offset += c.data.byteLength;
return view;
});
gltf.buffers = [{ byteLength: len }];
var json = new TextEncoder().encode(JSON.stringify(gltf));
var jsonPad = (4 - json.length % 4) % 4;
var binPad = (4 - len % 4) % 4;
var total = 12 + 8 + json.length + jsonPad + 8 + len + binPad;
var out = new Uint8Array(total);
var dv = new DataView(out.buffer);
dv.setUint32(0, 0x46546C67, true);
dv.setUint32(4, 2, true);
dv.setUint32(8, total, true);
dv.setUint32(12, json.length + jsonPad, true);
dv.setUint32(16, 0x4E4F534A, true);
out.set(json, 20);
for (var i = 0; i < jsonPad; i++) out[20 + json.length + i] = 0x20;
var p = 20 + json.length + jsonPad;
dv.setUint32(p, len + binPad, true);
dv.setUint32(p + 4, 0x004E4942, true);
out.set(bin, p + 8);
return out;
}
var geo = buildCube();
var png = pngBytes(drawTexture());
var gltf = {
asset: { version: '2.0' },
scene: 0,
scenes: [{ nodes: [0] }],
nodes: [{ mesh: 0 }],
meshes: [{
primitives: [{
attributes: { POSITION: 0, NORMAL: 1, TEXCOORD_0: 2 },
indices: 3,
material: 0
}]
}],
images: [{ bufferView: 4, mimeType: 'image/png' }],
samplers: [{ magFilter: 9729, minFilter: 9729, wrapS: 10497, wrapT: 10497 }],
textures: [{ sampler: 0, source: 0 }],
materials: [{
pbrMetallicRoughness: {
baseColorTexture: { index: 0 },
metallicFactor: 0.2,
roughnessFactor: 0.6
},
doubleSided: true
}],
accessors: [
{ bufferView: 0, componentType: 5126, count: 24, type: 'VEC3',
min: [-0.5, -0.5, -0.5], max: [0.5, 0.5, 0.5] },
{ bufferView: 1, componentType: 5126, count: 24, type: 'VEC3' },
{ bufferView: 2, componentType: 5126, count: 24, type: 'VEC2' },
{ bufferView: 3, componentType: 5123, count: 36, type: 'SCALAR' }
]
};
var glb = buildGlb(gltf, [
{ data: geo.pos, target: 34962 },
{ data: geo.nrm, target: 34962 },
{ data: geo.uv, target: 34962 },
{ data: geo.idx, target: 34963 },
{ data: png }
]);
var url = URL.createObjectURL(new Blob([glb], { type: 'model/gltf-binary' }));
var model = null;
/* 由局部轴向与偏移量算出世界坐标下的平面 */
var axis = new Cesium.Cartesian3();
function plane(nx, ny, nz, offsetMeters, keepPositive) {
axis = Cesium.Cartesian3.fromElements(nx, ny, nz, axis);
var nWorld = Cesium.Matrix4.multiplyByPointAsVector(
MATRIX, axis, new Cesium.Cartesian3()
);
Cesium.Cartesian3.normalize(nWorld, nWorld);
if (!keepPositive) Cesium.Cartesian3.negate(nWorld, nWorld);
var pWorld = Cesium.Matrix4.multiplyByPoint(
MATRIX,
new Cesium.Cartesian3(nx * offsetMeters, ny * offsetMeters, nz * offsetMeters),
new Cesium.Cartesian3()
);
return new Cesium.ClippingPlane(nWorld, -Cesium.Cartesian3.dot(nWorld, pWorld));
}
var inward = true;
function buildCollection(half) {
/* keepPositive 取反就能把「保留盒内」变成「保留盒外」 */
var sign = inward;
return new Cesium.ClippingPlaneCollection({
/* 保留盒外时,六个平面围出的被裁区域要取并集 */
unionClippingRegions: !inward,
planes: [
plane(1, 0, 0, half, !sign),
plane(-1, 0, 0, half, !sign),
plane(0, 1, 0, half, !sign),
plane(0, -1, 0, half, !sign),
plane(0, 0, 1, half, !sign),
plane(0, 0, -1, half, !sign)
],
edgeWidth: 2.0,
edgeColor: Cesium.Color.fromCssColorString('#ffb13d')
});
}
Cesium.Model.fromGltfAsync({ url: url, scale: 220 }).then(function (m) {
m.modelMatrix = MATRIX;
m.backFaceCulling = false;
if (m.clippingPlanesOriginMatrix) {
m.clippingPlanesOriginMatrix = Cesium.Matrix4.IDENTITY;
}
scene.primitives.add(m);
model = m;
m.clippingPlanes = buildCollection(110);
document.getElementById('info').textContent = '盒半径 110 米 · 保留盒内';
}).catch(function (err) {
document.getElementById('info').textContent = '解析失败:' + err.message;
});
document.getElementById('half').addEventListener('input', function () {
var h = parseInt(this.value, 10);
document.getElementById('hVal').textContent = h;
if (model) model.clippingPlanes = buildCollection(h);
});
document.getElementById('flip').addEventListener('click', function () {
inward = !inward;
var h = parseInt(document.getElementById('half').value, 10);
if (model) model.clippingPlanes = buildCollection(h);
document.getElementById('info').textContent = inward
? '盒半径 ' + h + ' 米 · 保留盒内' : '盒半径 ' + h + ' 米 · 保留盒外';
this.textContent = inward ? '反向裁剪' : '恢复盒内';
});
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(116.397, 39.898, 620),
orientation: {
heading: Cesium.Math.toRadians(40),
pitch: Cesium.Math.toRadians(-18),
roll: 0
},
duration: 0
});
})();
</script>
</body>
</html>
Language: the code and this page are in English; the full tutorial and API notes for this example are in Chinese. The demo itself is the authoritative version — it runs exactly as shown.