Atlaslog
Atlaslog / Examples / Cesium / 3D Models Coloring
Cesium · Runnable Example

3D Models Coloring

Runnable Cesium example: 3D Models Coloring. 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-3d-models-coloring.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/cesium-3d-models-coloring.html
<!--
  示例:同一个 GLB 模型用三种 colorBlendMode 摆在一起
  说明:模型二进制在内存里拼好交给 Model.fromGltfAsync,再用 HIGHLIGHT / MIX / REPLACE 三种着色方式渲染
  核心逻辑:Blob + createObjectURL 生成 GLB → 三份 Model → 调 color、colorBlendMode、colorBlendAmount
  依赖: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%}
  .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">左:HIGHLIGHT 中:MIX 右:REPLACE</div>
  <div class="row">混合比例 <span id="amtVal">0.6</span></div>
  <div class="row"><input id="amt" type="range" min="0" max="1" step="0.05" value="0.6"></div>
  <div class="row" id="info">正在解析模型…</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;

  /* ---------- 内存里拼一个单位立方体 GLB ---------- */
  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 = [], normals = [], 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.78, 0.8, 0.84, 1], metallicFactor: 0.1, roughnessFactor: 0.6 } }],
      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' }
      ]
    };

    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 modelUrl = URL.createObjectURL(new Blob([buildGlb()], { type: 'model/gltf-binary' }));
  var COLOR = Cesium.Color.fromCssColorString('#4d9bff');
  var modes = [
    { name: 'HIGHLIGHT', lon: 116.3840, amt: 0.55 },
    { name: 'MIX',       lon: 116.3913, amt: 0.60 },
    { name: 'REPLACE',   lon: 116.3986, amt: 0.00 }
  ];
  var models = [];

  modes.forEach(function (m) {
    Cesium.Model.fromGltfAsync({
      url: modelUrl,
      scale: 260,
      minimumPixelSize: 40,
      color: COLOR,
      colorBlendMode: Cesium.ColorBlendMode[m.name],
      colorBlendAmount: m.amt
    }).then(function (model) {
      model.modelMatrix = Cesium.Transforms.eastNorthUpToFixedFrame(
        Cesium.Cartesian3.fromDegrees(m.lon, 39.907359, 0)
      );
      scene.primitives.add(model);
      models.push({ model: model, mode: m.name });
      document.getElementById('info').textContent = '36 个三角面 · 3 份实例 · 内联 GLB';
    }).catch(function (err) {
      document.getElementById('info').textContent = '解析失败:' + err.message;
    });

    viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(m.lon, 39.907359, 300),
      label: {
        text: m.name,
        font: '500 12px "Microsoft YaHei", sans-serif',
        fillColor: Cesium.Color.WHITE,
        pixelOffset: new Cesium.Cartesian2(0, -10),
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      }
    });
  });

  document.getElementById('amt').addEventListener('input', function () {
    var v = parseFloat(this.value);
    document.getElementById('amtVal').textContent = v.toFixed(2);
    models.forEach(function (item) {
      if (item.mode !== 'REPLACE') item.model.colorBlendAmount = v;
    });
  });

  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(116.3913, 39.9020, 1250),
    orientation: {
      heading: Cesium.Math.toRadians(0),
      pitch: Cesium.Math.toRadians(-28),
      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 · EXAMPLE3D Models Dev Cesium · EXAMPLE3D Models Node Explorer Dev Cesium · EXAMPLE3D Tiles 1.1 Cdb Yemen