Atlaslog
Atlaslog / Examples / Cesium / Model Load
Cesium · Runnable Example

Model Load

Runnable Cesium example: Model Load. Open the live demo, read the complete source, and copy the file into your project. No build step or API key.

Open standalone → Chinese notes All Cesium examples
/demos/cesium-model-load.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/cesium-model-load.html
<!--
  示例:加载一个内联 glTF 模型
  要点:页面内拼出 GLB 二进制并用 Blob URL 交给 Model.fromGltfAsync,再调 scale 与颜色混合模式
  依赖: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>模型加载</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:7px}
  input[type=range]{width:100%}
  select{font:inherit;font-size:12px;background:#1d232b;color:#cfd6e2;
       border:1px solid #343b46;border-radius:4px;padding:2px 4px;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>内联 glTF 模型</b></div>
  <div class="row" id="info">正在解析模型…</div>
  <div class="row">缩放 <span id="scaleVal">150</span> 米</div>
  <div class="row"><input id="scale" type="range" min="20" max="400" step="10" value="150"></div>
  <div class="row">混合模式</div>
  <div class="row">
    <select id="blend">
      <option value="HIGHLIGHT">HIGHLIGHT 高亮</option>
      <option value="MIX">MIX 混合</option>
      <option value="REPLACE">REPLACE 替换</option>
    </select>
  </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;
  scene.globe.enableLighting = true;

  var CENTER = Cesium.Cartesian3.fromDegrees(116.391263, 39.907359, 0);
  var COLOR = Cesium.Color.fromCssColorString('#4d9bff');

  /* ---------- 在内存里拼一个 GLB:单位立方体,底面落在 y = 0 ---------- */
  function buildGlb() {
    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 positions = [];
    var normals = [];
    var indices = [];

    faces.forEach(function (f, fi) {
      f.v.forEach(function (p) {
        positions.push(p[0] * 0.5, p[1] * 0.5 + 0.5, p[2] * 0.5);
        normals.push(f.n[0], f.n[1], f.n[2]);
      });
      var b = fi * 4;
      indices.push(b, b + 1, b + 2, b, b + 2, b + 3);
    });

    var posBytes = new Uint8Array(new Float32Array(positions).buffer);
    var nrmBytes = new Uint8Array(new Float32Array(normals).buffer);
    var idxBytes = new Uint8Array(new Uint16Array(indices).buffer);

    var bin = new Uint8Array(posBytes.length + nrmBytes.length + idxBytes.length);
    bin.set(posBytes, 0);
    bin.set(nrmBytes, posBytes.length);
    bin.set(idxBytes, posBytes.length + nrmBytes.length);

    var gltf = {
      asset: { version: '2.0' },
      scene: 0,
      scenes: [{ nodes: [0] }],
      nodes: [{ mesh: 0 }],
      meshes: [{ primitives: [{ attributes: { POSITION: 0, NORMAL: 1 }, indices: 2, material: 0 }] }],
      materials: [{
        pbrMetallicRoughness: {
          baseColorFactor: [0.62, 0.72, 0.86, 1.0],
          metallicFactor: 0.15,
          roughnessFactor: 0.55
        }
      }],
      buffers: [{ byteLength: bin.length }],
      bufferViews: [
        { buffer: 0, byteOffset: 0, byteLength: posBytes.length, target: 34962 },
        { buffer: 0, byteOffset: posBytes.length, byteLength: nrmBytes.length, target: 34962 },
        { buffer: 0, byteOffset: posBytes.length + nrmBytes.length, byteLength: idxBytes.length, target: 34963 }
      ],
      accessors: [
        {
          bufferView: 0, componentType: 5126, count: 24, type: 'VEC3',
          min: [-0.5, 0, -0.5], max: [0.5, 1, 0.5]
        },
        { bufferView: 1, componentType: 5126, count: 24, type: 'VEC3' },
        { bufferView: 2, componentType: 5123, count: 36, type: 'SCALAR' }
      ]
    };

    /* GLB 容器:12 字节头 + JSON 块 + BIN 块,块长度按 4 字节对齐 */
    var jsonBytes = new TextEncoder().encode(JSON.stringify(gltf));
    var jsonPad = (4 - jsonBytes.length % 4) % 4;
    var binPad = (4 - bin.length % 4) % 4;
    var total = 12 + 8 + jsonBytes.length + jsonPad + 8 + bin.length + 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, jsonBytes.length + jsonPad, true);
    dv.setUint32(16, 0x4E4F534A, true);
    out.set(jsonBytes, 20);
    for (var i = 0; i < jsonPad; i++) out[20 + jsonBytes.length + i] = 0x20;

    var offset = 20 + jsonBytes.length + jsonPad;
    dv.setUint32(offset, bin.length + binPad, true);
    dv.setUint32(offset + 4, 0x004E4942, true);
    out.set(bin, offset + 8);

    return out;
  }

  var model = null;
  var modelUrl = URL.createObjectURL(new Blob([buildGlb()], { type: 'model/gltf-binary' }));

  Cesium.Model.fromGltfAsync({
    url: modelUrl,
    scale: 150,
    minimumPixelSize: 28,
    color: COLOR,
    colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT,
    colorBlendAmount: 0.55
  }).then(function (m) {
    m.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(CENTER);
    scene.primitives.add(m);
    model = m;
    document.getElementById('info').textContent = '36 个三角面 · 内置 glTF 2.0';
  }).catch(function (err) {
    document.getElementById('info').textContent = '解析失败:' + err.message;
  });

  viewer.entities.add({
    position: CENTER,
    label: {
      text: '内联模型',
      font: '500 12px "Microsoft YaHei", sans-serif',
      fillColor: Cesium.Color.WHITE,
      pixelOffset: new Cesium.Cartesian2(0, -6),
      disableDepthTestDistance: Number.POSITIVE_INFINITY
    }
  });

  document.getElementById('scale').addEventListener('input', function () {
    var v = parseInt(this.value, 10);
    document.getElementById('scaleVal').textContent = v;
    if (model) model.scale = v;
  });

  document.getElementById('blend').addEventListener('change', function () {
    if (!model) return;
    model.colorBlendMode = Cesium.ColorBlendMode[this.value];
    model.colorBlendAmount = this.value === 'MIX' ? 0.6 : 0.0;
  });

  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(116.368, 39.889, 620),
    orientation: {
      heading: Cesium.Math.toRadians(38),
      pitch: Cesium.Math.toRadians(-22),
      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.

More Cesium examples

Cesium · EXAMPLEModel Texture Glb Cesium · EXAMPLEMoon Cesium · EXAMPLEMouse Pick