Atlaslog
Atlaslog / Examples / Cesium / Drag Draw Polygon
Cesium · Runnable Example

Drag Draw Polygon

Runnable Cesium example: Drag Draw Polygon. 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-drag-draw-polygon.htmlLIVE
single HTML file · CDN dependencies onlyinterface may contain Chinese labels

Source

demos/cesium-drag-draw-polygon.html
<!--
  示例:按住左键在地面拖出一条多边形
  要点:mousedown 关掉相机旋转,move 时不断取射线与地表交点,mouseup 收尾
  依赖: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:6px}
  .hud button{font:inherit;font-size:12px;padding:3px 9px;border-radius:4px;cursor:pointer;
       border:1px solid #343b46;background:#1d232b;color:#cfd6e2}
  .mono{font-family:ui-monospace,Consolas,monospace;font-size:11px;color:#8fb7e0}
  .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">按住左键划出一片区域</div>
  <div class="row mono" id="cnt">已绘 0 个多边形</div>
  <div class="row"><button id="clear">清空全部</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('#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 COLORS = ['#4d9bff', '#5fd0a8', '#ffb13d', '#e35d6a', '#9b7bff'];
  var count = 0;
  var drawing = null;

  /* 把屏幕坐标换成地表点 */
  function groundAt(windowPosition) {
    var ray = viewer.camera.getPickRay(windowPosition);
    return ray ? scene.globe.pick(ray, scene) : undefined;
  }

  var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);

  handler.setInputAction(function (down) {
    var p = groundAt(down.position);
    if (!Cesium.defined(p)) return;

    var positions = [p];
    var color = Cesium.Color.fromCssColorString(COLORS[count % COLORS.length]);
    count++;

    var polygon = viewer.entities.add({
      polygon: {
        hierarchy: new Cesium.CallbackProperty(function () {
          return new Cesium.PolygonHierarchy(positions.slice());
        }, false),
        material: color.withAlpha(0.32)
      }
    });

    var edge = viewer.entities.add({
      polyline: {
        positions: new Cesium.CallbackProperty(function () {
          return positions.slice();
        }, false),
        width: 2,
        material: new Cesium.ColorMaterialProperty(color),
        clampToGround: true
      }
    });

    drawing = { positions: positions, polygon: polygon, edge: edge };
    scene.screenSpaceCameraController.enableRotate = false;
  }, Cesium.ScreenSpaceEventType.LEFT_DOWN);

  handler.setInputAction(function (move) {
    if (!drawing) return;
    var p = groundAt(move.endPosition);
    if (!Cesium.defined(p)) return;

    /* 距离上一个点太近就不追加,避免顶点过密 */
    var last = drawing.positions[drawing.positions.length - 1];
    if (Cesium.Cartesian3.distance(last, p) < 12) return;
    drawing.positions.push(p);
  }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

  handler.setInputAction(function () {
    if (!drawing) return;
    scene.screenSpaceCameraController.enableRotate = true;

    if (drawing.positions.length < 3) {
      viewer.entities.remove(drawing.polygon);
      viewer.entities.remove(drawing.edge);
    } else {
      /* 顶点少于三个时退回,否则保留成一个闭合面 */
      drawing.polygon.polygon.outline = true;
      drawing.polygon.polygon.outlineColor = Cesium.Color.fromCssColorString('#eaf2ff');
    }
    drawing = null;
    document.getElementById('cnt').textContent = '已绘 ' + count + ' 个多边形';
  }, Cesium.ScreenSpaceEventType.LEFT_UP);

  document.getElementById('clear').addEventListener('click', function () {
    viewer.entities.removeAll();
    count = 0;
    document.getElementById('cnt').textContent = '已绘 0 个多边形';
  });

  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(116.389, 39.888, 5200),
    orientation: {
      heading: 0,
      pitch: Cesium.Math.toRadians(-55),
      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 · EXAMPLEDrawing on Terrain Cesium · EXAMPLEDynamic Wall Cesium · EXAMPLEEarth At Night