Atlaslog
Atlaslog / Examples / Cesium / Polygon Hole Mask
Cesium · Runnable Example

Polygon Hole Mask

Runnable Cesium example: Polygon Hole Mask. 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-polygon-hole-mask.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/cesium-polygon-hole-mask.html
<!--
  示例:在多边形上挖出圆形空洞
  要点:PolygonHierarchy 第二个参数是洞的数组,每个洞本身也是一圈坐标
  依赖: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,.92);
       border:1px solid #2a313b;border-radius:6px;padding:9px 12px;font-size:12px;
       color:#a2a9b6;width:252px}
  .hud b{color:#e6e8ec;font-weight:600}
  .hud .row{margin-top:7px}
  input[type=range]{width:100%}
  .hud button{font:inherit;font-size:12px;padding:3px 9px;border-radius:4px;cursor:pointer;
       border:1px solid #343b46;background:#1d232b;color:#cfd6e2;margin-top:8px}
  .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="rVal">900</span> 米</div>
  <div class="row"><input id="radius" type="range" min="300" max="2200" step="50" value="900"></div>
  <div class="row"><button id="toggle">去掉洞</button></div>
  <div class="row">洞内的标记点保持可见</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('#16202c');
  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 = { lng: 116.389, lat: 39.906 };
  var OUTER = [
    [116.356, 39.874], [116.424, 39.874],
    [116.424, 39.938], [116.356, 39.938]
  ];

  var HOLE_CENTERS = [
    [116.372, 39.896], [116.406, 39.916]
  ];

  /* 生成一圈圆环顶点,用来当洞的边界 */
  function circleRing(lng, lat, radius) {
    var pts = [];
    var mPerDegLng = 111320 * Math.cos(Cesium.Math.toRadians(lat));
    var mPerDegLat = 111320;
    for (var i = 0; i < 48; i++) {
      var a = i / 48 * Math.PI * 2;
      pts.push(lng + Math.cos(a) * radius / mPerDegLng);
      pts.push(lat + Math.sin(a) * radius / mPerDegLat);
    }
    return Cesium.Cartesian3.fromDegreesArray(pts);
  }

  var outerPositions = Cesium.Cartesian3.fromDegreesArray([
    OUTER[0][0], OUTER[0][1], OUTER[1][0], OUTER[1][1],
    OUTER[2][0], OUTER[2][1], OUTER[3][0], OUTER[3][1]
  ]);

  var radius = 900;
  var holesOn = true;

  var holes = HOLE_CENTERS.map(function (h) {
    return new Cesium.PolygonHierarchy(circleRing(h[0], h[1], radius));
  });

  var mask = viewer.entities.add({
    polygon: {
      hierarchy: new Cesium.PolygonHierarchy(outerPositions, holes),
      height: 0,
      material: Cesium.Color.fromCssColorString('#0d1620').withAlpha(0.86)
    }
  });

  /* 每个洞中心的标记,遮罩生效时依然可见 */
  HOLE_CENTERS.forEach(function (h, i) {
    viewer.entities.add({
      position: Cesium.Cartesian3.fromDegrees(h[0], h[1], 40),
      cylinder: {
        length: 80, topRadius: 6, bottomRadius: 26,
        material: Cesium.Color.fromCssColorString(i === 0 ? '#ffb13d' : '#5fd0a8')
      },
      label: {
        text: '洞 ' + (i + 1) + ' 中心',
        font: '500 12px "Microsoft YaHei", sans-serif',
        fillColor: Cesium.Color.WHITE,
        pixelOffset: new Cesium.Cartesian2(0, -14),
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      }
    });
  });

  /* 遮罩外框 */
  viewer.entities.add({
    polyline: {
      positions: Cesium.Cartesian3.fromDegreesArray([
        OUTER[0][0], OUTER[0][1], OUTER[1][0], OUTER[1][1],
        OUTER[2][0], OUTER[2][1], OUTER[3][0], OUTER[3][1],
        OUTER[0][0], OUTER[0][1]
      ]),
      width: 2,
      material: new Cesium.PolylineDashMaterialProperty({
        color: Cesium.Color.fromCssColorString('#ffb13d'),
        dashLength: 20
      }),
      clampToGround: true
    }
  });

  document.getElementById('radius').addEventListener('input', function () {
    radius = parseFloat(this.value);
    document.getElementById('rVal').textContent = this.value;
    if (!holesOn) return;
    mask.polygon.hierarchy = new Cesium.PolygonHierarchy(
      outerPositions,
      HOLE_CENTERS.map(function (h) {
        return new Cesium.PolygonHierarchy(circleRing(h[0], h[1], radius));
      })
    );
  });

  document.getElementById('toggle').addEventListener('click', function () {
    holesOn = !holesOn;
    mask.polygon.hierarchy = holesOn
      ? new Cesium.PolygonHierarchy(
          outerPositions,
          HOLE_CENTERS.map(function (h) {
            return new Cesium.PolygonHierarchy(circleRing(h[0], h[1], radius));
          })
        )
      : new Cesium.PolygonHierarchy(outerPositions);
    this.textContent = holesOn ? '去掉洞' : '恢复洞';
  });

  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(116.389, 39.860, 11000),
    orientation: {
      heading: 0,
      pitch: Cesium.Math.toRadians(-62),
      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 · EXAMPLEPolyline Cesium · EXAMPLEPolyline Dash Cesium · EXAMPLEPolylines on 3D Tiles