Model Animation
Runnable Cesium example: Model Animation. 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
<!--
示例:让内联 GLB 里的节点自己转起来
要点:GLB 内写入 rotation 动画通道,模型加载后用 activeAnimations.addAll 循环播放
依赖:CesiumJS 1.121 · jsDelivr CDN,模型与动画关键帧都在内存中生成
-->
<!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>GLB 节点动画</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,.9);
border:1px solid #2a313b;border-radius:6px;padding:9px 12px;font-size:12px;
color:#a2a9b6;max-width:250px}
.hud b{color:#e6e8ec;font-weight:600}
.hud .row{margin-top:6px}
input[type=range]{width:100%}
.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="spVal">1.0</span> 倍</div>
<div class="row"><input id="sp" type="range" min="0" max="4" step="0.25" value="1"></div>
<div class="row" id="info">正在解析 GLB…</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, 58);
/* ---------- 单位立方体:位置、法线、索引 ---------- */
function cube() {
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 pos = [], nrm = [], idx = [];
faces.forEach(function (f, fi) {
f.v.forEach(function (p) {
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]);
});
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),
idx: new Uint16Array(idx)
};
}
/* ---------- 组装 GLB:chunks 顺序即 bufferView 顺序 ---------- */
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 = cube();
/* 每 90° 一个关键帧,共 2.5 秒一圈 */
var times = new Float32Array([0, 0.625, 1.25, 1.875, 2.5]);
var quats = new Float32Array(20);
for (var k = 0; k < 5; k++) {
var half = (k * Math.PI / 2) / 2;
quats[k * 4] = 0;
quats[k * 4 + 1] = Math.sin(half);
quats[k * 4 + 2] = 0;
quats[k * 4 + 3] = Math.cos(half);
}
var gltf = {
asset: { version: '2.0' },
scene: 0,
scenes: [{ nodes: [0, 1] }],
/* 节点 0 是轮毂,节点 1 是横贯的长桨,绕 Y 轴旋转 */
nodes: [
{ mesh: 0, scale: [0.34, 0.26, 0.34] },
{ mesh: 0, scale: [1.5, 0.09, 0.12] }
],
meshes: [{ primitives: [{ attributes: { POSITION: 0, NORMAL: 1 }, indices: 2, material: 0 }] }],
materials: [{
pbrMetallicRoughness: {
baseColorFactor: [0.42, 0.74, 0.95, 1.0],
metallicFactor: 0.2,
roughnessFactor: 0.4
}
}],
animations: [{
samplers: [{ input: 3, output: 4, interpolation: 'LINEAR' }],
channels: [{ sampler: 0, target: { node: 1, path: 'rotation' } }]
}],
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: 5123, count: 36, type: 'SCALAR' },
{ bufferView: 3, componentType: 5126, count: 5, type: 'SCALAR', min: [0], max: [2.5] },
{ bufferView: 4, componentType: 5126, count: 5, type: 'VEC4' }
]
};
var glb = buildGlb(gltf, [
{ data: geo.pos, target: 34962 },
{ data: geo.nrm, target: 34962 },
{ data: geo.idx, target: 34963 },
{ data: times },
{ data: quats }
]);
var url = URL.createObjectURL(new Blob([glb], { type: 'model/gltf-binary' }));
var model = null;
var rotor = null;
Cesium.Model.fromGltfAsync({ url: url, scale: 70 }).then(function (m) {
m.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(CENTER);
scene.primitives.add(m);
model = m;
rotor = m.activeAnimations.addAll({
loop: Cesium.ModelAnimationLoop.REPEAT,
speed: 1.0
})[0];
document.getElementById('info').textContent = '1 条 rotation 通道 · 5 个关键帧';
}).catch(function (err) {
document.getElementById('info').textContent = '解析失败:' + err.message;
});
/* 地面标签与支柱,交代模型落点 */
viewer.entities.add({
position: Cesium.Cartesian3.fromDegrees(116.389, 39.906, 0),
cylinder: {
length: 58, topRadius: 3, bottomRadius: 5,
material: Cesium.Color.fromCssColorString('#5b6573')
},
label: {
text: 'GLB 节点动画',
font: '500 12px "Microsoft YaHei", sans-serif',
fillColor: Cesium.Color.WHITE,
pixelOffset: new Cesium.Cartesian2(0, 8),
disableDepthTestDistance: Number.POSITIVE_INFINITY
}
});
document.getElementById('sp').addEventListener('input', function () {
var v = parseFloat(this.value);
document.getElementById('spVal').textContent = v.toFixed(2);
if (rotor) rotor.speed = v;
});
viewer.camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(116.383, 39.899, 380),
orientation: {
heading: Cesium.Math.toRadians(20),
pitch: Cesium.Math.toRadians(-16),
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.