Atlaslog
Atlaslog / Examples / Cesium / Terrain Clamp Entity
Cesium · Runnable Example

Terrain Clamp Entity

Runnable Cesium example: Terrain Clamp Entity. 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-terrain-clamp-entity.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/cesium-terrain-clamp-entity.html
<!--
  示例:自造起伏地形,再把实体贴到地表
  要点:CustomHeightmapTerrainProvider 供高程,clampToGround 让点线面跟随地形
  依赖: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:260px}
  .hud b{color:#e6e8ec;font-weight:600}
  .hud .row{margin-top:6px}
  .hud .k{color:#8fb7e0;font-family:ui-monospace,Consolas,monospace}
  .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 class="k" id="h1">—</span> 米</div>
  <div class="row">最高点:<span class="k" id="h2">—</span> 米</div>
  <div class="row">点、线、面全部 clampToGround</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 SIZE = 32;
  var CLNG = 116.30;
  var CLAT = 39.98;

  function heightAt(lng, lat) {
    var dx = (lng - CLNG) / 0.30;
    var dy = (lat - CLAT) / 0.24;
    var r = Math.sqrt(dx * dx + dy * dy);
    if (r > 1.6) return 0;
    var dome = 1800 * Math.cos(r * Math.PI / 3.2);
    var ridge = 420 * Math.sin(lng * 42.0) * Math.cos(lat * 36.0);
    return Math.max(0, dome + ridge);
  }

  viewer.terrainProvider = new Cesium.CustomHeightmapTerrainProvider({
    width: SIZE,
    height: SIZE,
    tilingScheme: new Cesium.GeographicTilingScheme(),
    callback: function (x, y, level) {
      var map = new Float32Array(SIZE * SIZE);
      var tiles = Math.pow(2, level);
      for (var j = 0; j < SIZE; j++) {
        for (var i = 0; i < SIZE; i++) {
          var lng = ((x + (i + 0.5) / SIZE) / tiles) * 360 - 180;
          var lat = 90 - ((y + (j + 0.5) / SIZE) / tiles) * 180;
          map[j * SIZE + i] = heightAt(lng, lat);
        }
      }
      return map;
    }
  });

  /* 贴地的面:覆盖山顶的一块椭圆 */
  viewer.entities.add({
    position: Cesium.Cartesian3.fromDegrees(CLNG, CLAT),
    ellipse: {
      semiMajorAxis: 5200,
      semiMinorAxis: 3800,
      material: Cesium.Color.fromCssColorString('#4d9bff').withAlpha(0.32),
      outline: true,
      outlineColor: Cesium.Color.fromCssColorString('#9fd0ff'),
      heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
    }
  });

  /* 贴地的线:从山脚翻过山脊 */
  var ridgeLine = [];
  for (var i = 0; i <= 16; i++) {
    ridgeLine.push(CLNG - 0.16 + i * 0.02, CLAT - 0.10 + i * 0.012);
  }
  viewer.entities.add({
    polyline: {
      positions: Cesium.Cartesian3.fromDegreesArray(ridgeLine),
      width: 3,
      material: Cesium.Color.fromCssColorString('#ffb13d'),
      clampToGround: true
    }
  });

  /* 贴地的点与分米级标签 */
  var PEAKS = [
    [CLNG, CLAT + 0.055, '主峰'],
    [CLNG - 0.10, CLAT - 0.05, '西坡'],
    [CLNG + 0.11, CLAT - 0.02, '东坡']
  ];
  PEAKS.forEach(function (p) {
    viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(p[0], p[1]),
      point: {
        pixelSize: 8,
        color: Cesium.Color.fromCssColorString('#5fd0a8'),
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      },
      label: {
        text: p[2],
        font: '500 12px "Microsoft YaHei", sans-serif',
        fillColor: Cesium.Color.WHITE,
        pixelOffset: new Cesium.Cartesian2(0, -18),
        heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      }
    });
  });

  /* 采样实际高程,验证贴地位置与地形一致 */
  var probe = Cesium.Cartographic.fromDegrees(CLNG, CLAT);
  Cesium.sampleTerrainMostDetailed(viewer.terrainProvider, [probe]).then(function (result) {
    document.getElementById('h1').textContent = Math.round(result[0].height);
  });

  var samples = [];
  for (var k = 0; k < 9; k++) {
    samples.push(Cesium.Cartographic.fromDegrees(CLNG - 0.16 + k * 0.04, CLAT));
  }
  Cesium.sampleTerrainMostDetailed(viewer.terrainProvider, samples).then(function (result) {
    var max = 0;
    result.forEach(function (c) { max = Math.max(max, c.height); });
    document.getElementById('h2').textContent = Math.round(max);
  });

  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(CLNG - 0.13, CLAT - 0.16, 15000),
    orientation: {
      heading: Cesium.Math.toRadians(24),
      pitch: Cesium.Math.toRadians(-24),
      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 · EXAMPLETerrain Clipping Planes Cesium · EXAMPLETerrain Exaggeration Cesium · EXAMPLETime Availability