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

Model Distance

Runnable Cesium example: Model Distance. 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-distance.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/cesium-model-distance.html
<!--
  示例:按相机距离决定模型是否显示
  要点:ModelGraphics 的 distanceDisplayCondition 设置可见区间,近远两档拼出连续层次
  依赖:CesiumJS 1.121 · jsDelivr CDN,模型由 Blob 现场生成
-->
<!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:252px}
  .hud b{color:#e6e8ec;font-weight:600}
  .hud .row{margin-top:6px}
  .hud button{font:inherit;font-size:12px;padding:3px 9px;margin-right:4px;border-radius:4px;
       cursor:pointer;border:1px solid #343b46;background:#1d232b;color:#cfd6e2}
  .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">
    <button id="near">拉到近处</button>
    <button id="far">退到远处</button>
  </div>
  <div class="row" id="dist">相机距目标 —</div>
  <div class="row">近模型 &lt; 600 米 · 远模型 700~4000 米</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, 0);

  /* 最简立方体 GLB */
  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 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)
    };
  }

  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 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.5, 0.75, 1.0, 1.0],
        metallicFactor: 0.2,
        roughnessFactor: 0.4
      }
    }],
    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' }
    ]
  };

  var glb = buildGlb(gltf, [
    { data: geo.pos, target: 34962 },
    { data: geo.nrm, target: 34962 },
    { data: geo.idx, target: 34963 }
  ]);
  var MODEL_URL = URL.createObjectURL(new Blob([glb], { type: 'model/gltf-binary' }));

  /* 近处显示的小模型:距离在 600 米以内可见 */
  viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(116.389, 39.906, 260),
    model: {
      uri: MODEL_URL,
      scale: 260,
      minimumPixelSize: 24,
      distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 600)
    },
    label: {
      text: '近模型 0~600m',
      font: '500 12px "Microsoft YaHei", sans-serif',
      fillColor: Cesium.Color.fromCssColorString('#7ab6ff'),
      pixelOffset: new Cesium.Cartesian2(0, -12),
      distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 600),
      disableDepthTestDistance: Number.POSITIVE_INFINITY
    }
  });

  /* 远处显示的替代模型:700 米之外才出现,避免同时叠在一起 */
  viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(116.389, 39.906, 1200),
    model: {
      uri: MODEL_URL,
      scale: 1500,
      minimumPixelSize: 30,
      distanceDisplayCondition: new Cesium.DistanceDisplayCondition(700, 4000)
    },
    label: {
      text: '远模型 700~4000m',
      font: '500 12px "Microsoft YaHei", sans-serif',
      fillColor: Cesium.Color.fromCssColorString('#ffb13d'),
      pixelOffset: new Cesium.Cartesian2(0, -12),
      distanceDisplayCondition: new Cesium.DistanceDisplayCondition(700, 4000),
      disableDepthTestDistance: Number.POSITIVE_INFINITY
    }
  });

  viewer.entities.add({
    position: CENTER,
    point: {
      pixelSize: 7,
      color: Cesium.Color.fromCssColorString('#eaf2ff'),
      disableDepthTestDistance: Number.POSITIVE_INFINITY
    }
  });

  var distEl = document.getElementById('dist');
  var eye = new Cesium.Cartesian3();

  scene.postRender.addEventListener(function () {
    Cesium.Cartesian3.subtract(viewer.camera.positionWC, CENTER, eye);
    var d = Cesium.Cartesian3.magnitude(eye);
    distEl.textContent = '相机距目标 ' + Math.round(d) + ' 米 · ' +
      (d <= 600 ? '只见近模型' : d >= 700 && d <= 4000 ? '只见远模型' : '两者都隐藏');
  });

  function moveTo(height, pitch) {
    viewer.camera.setView({
      destination: Cesium.Cartesian3.fromDegrees(116.389, 39.895, height),
      orientation: {
        heading: 0,
        pitch: Cesium.Math.toRadians(pitch),
        roll: 0
      }
    });
  }

  document.getElementById('near').addEventListener('click', function () { moveTo(320, -12); });
  document.getElementById('far').addEventListener('click', function () { moveTo(2400, -30); });

  moveTo(2400, -30);
})();
</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 Hpr Cesium · EXAMPLEModel Load Cesium · EXAMPLEModel Texture Glb