cesium 知识点

好,不带链接,直接把 CesiumJS 从入门到精通的核心知识点全部整理成文字给你,照着学就行👇


🌍 CesiumJS 从入门到精通 核心知识点全集


一、Cesium 是什么

  • 基于 WebGL 的开源 JS 库,用于创建三维地球/地图
  • 核心渲染:WGS84 椭球体 + 地形 + 影像 + 3D Tiles + Entity/Primitive
  • 开发依赖:JS/TS + ES6 + 前端框架(Vue/React 均可)

二、环境初始化(入门第一件事)

npm 安装

复制代码
npm install cesium

最小初始化

js 复制代码
import * as Cesium from 'cesium';
const viewer = new Cesium.Viewer('cesiumContainer', {
  terrainProvider: Cesium.createWorldTerrain()
});

Viewer 常用关闭项

  • animation:左下角动画控件
  • timeline:底部时间轴
  • baseLayerPicker:底图选择器
  • navigationHelpButton:帮助按钮
  • fullscreenButton:全屏

三、坐标系(最重要基础)

说明
Cesium.Cartesian3 笛卡尔坐标(x,y,z),Cesium 内部计算用
Cesium.Cartographic 经纬度+高度(弧度),lon/lat/height
Cesium.Cartesian2 屏幕像素坐标

经纬度 → 笛卡尔

js 复制代码
const pos = Cesium.Cartesian3.fromDegrees(116.39, 39.9, 100);
// 参数顺序:(经度, 纬度, 高度)

笛卡尔 → 经纬度

js 复制代码
const carto = Cesium.Cartographic.fromCartesian(pos);
const lon = Cesium.Math.toDegrees(carto.longitude);
const lat = Cesium.Math.toDegrees(carto.latitude);
const h = carto.height;

⚠️ Cartographic 的 longitude/latitude 是弧度,必须 toDegrees 转角度


四、Viewer / Scene / Camera

Viewer

  • 应用入口,包含 Scene、Camera、DataSourceCollection、Timeline
  • viewer.scene → 场景
  • viewer.camera → 相机
  • viewer.entities → Entity 集合
  • viewer.dataSources → 外部数据(GeoJSON/KML/CZML)
  • viewer.imageryLayers → 影像图层
  • viewer.scene.primitives → Primitive 集合

Scene 常用

js 复制代码
viewer.scene.globe.enableLighting = true;   // 太阳光照
viewer.scene.globe.depthTestAgainstTerrain = true; // 开启深度检测(贴地)
viewer.scene.skyAtmosphere.show = false;    // 关大气
viewer.scene.requestRenderMode = true;      // 按需渲染(性能优化)

Camera 控制

js 复制代码
// 飞到某位置
viewer.camera.flyTo({
  destination: Cesium.Cartesian3.fromDegrees(116.4, 39.9, 2000),
  orientation: {
    heading: Cesium.Math.toRadians(0),
    pitch: Cesium.Math.toRadians(-45),
    roll: 0
  },
  duration: 3
});

// 锁定视角看某点
viewer.camera.lookAt(targetPosition, new Cesium.Cartesian3(0, -1000, 500));

五、影像 & 地形

影像图层(ImageryProvider)

js 复制代码
// 添加 ArcGIS 影像
viewer.imageryLayers.addImageryProvider(
  new Cesium.ArcGisMapServerImageryProvider({
    url: 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer'
  })
);

支持:WMS / WMTS / TMS / BingMaps / ArcGIS / SingleTile

地形(TerrainProvider)

js 复制代码
viewer.terrainProvider = Cesium.createWorldTerrain({
  requestWaterMask: true,     // 水面效果
  requestVertexNormals: true   // 光照法线
});

六、Entity API(业务开发首选)

添加点

js 复制代码
viewer.entities.add({
  position: Cesium.Cartesian3.fromDegrees(116.39, 39.9, 50),
  point: { pixelSize: 10, color: Cesium.Color.RED },
  label: { text: '北京', font: '14px sans-serif' }
});

线

js 复制代码
viewer.entities.add({
  polyline: {
    positions: Cesium.Cartesian3.fromDegreesArray([116.3,39.9, 116.5,40.0]),
    width: 3,
    material: Cesium.Color.YELLOW
  }
});

面(Polygon)

js 复制代码
viewer.entities.add({
  polygon: {
    hierarchy: Cesium.Cartesian3.fromDegreesArray([
      116.3,39.8, 116.5,39.8, 116.5,40.0, 116.3,40.0
    ]),
    material: Cesium.Color.BLUE.withAlpha(0.5),
    outline: true,
    outlineColor: Cesium.Color.WHITE
  }
});

广告牌(Billboard) / 模型(glTF)

js 复制代码
// 图标
viewer.entities.add({
  position: Cesium.Cartesian3.fromDegrees(116.4, 39.9),
  billboard: { image: 'icon.png', width: 32, height: 32 }
});

// glTF 模型
viewer.entities.add({
  position: Cesium.Cartesian3.fromDegrees(116.4, 39.9, 0),
  model: {
    uri: 'model.glb',
    scale: 1.0,
    minimumPixelSize: 64
  }
});

动态属性(时间驱动)

  • CallbackProperty 实现位置/颜色实时更新
  • SampledPositionProperty + Clock 做轨迹回放

七、DataSource(加载外部数据)

js 复制代码
// GeoJSON
viewer.dataSources.add(Cesium.GeoJsonDataSource.load('china.json', {
  stroke: Cesium.Color.YELLOW,
  fill: Cesium.Color.RED.withAlpha(0.3)
}));

// KML
viewer.dataSources.add(Cesium.KmlDataSource.load('data.kml'));

// CZML(带时间动态)
viewer.dataSources.add(Cesium.CzmlDataSource.load('route.czml'));

八、Primitive API(高性能/大量数据)

Entity < 1万 用 Entity;> 1万点或需自定义着色器用 Primitive

基本结构:Geometry + Appearance

js 复制代码
const primitive = new Cesium.Primitive({
  geometryInstances: new Cesium.GeometryInstance({
    geometry: new Cesium.RectangleGeometry({
      rectangle: Cesium.Rectangle.fromDegrees(116, 39.8, 116.5, 40),
      vertexFormat: Cesium.EllipsoidSurfaceAppearance.VERTEX_FORMAT,
      height: 10000
    }),
    attributes: {
      color: Cesium.ColorGeometryInstanceAttribute.fromColor(
        Cesium.Color.RED.withAlpha(0.6)
      )
    }
  }),
  appearance: new Cesium.PerInstanceColorAppearance(),
  asynchronous: false
});
viewer.scene.primitives.add(primitive);

专用集合(推荐大量点/图标/文字)

  • PointPrimitiveCollection --- 大量点
  • BillboardCollection --- 大量图标
  • LabelCollection --- 大量文字
  • PolylineCollection --- 大量线
  • GroundPrimitive --- 贴地几何
  • GroundPolylinePrimitive --- 贴地折线

九、3D Tiles(倾斜摄影/BIM/城市模型)

js 复制代码
const tileset = await Cesium.Cesium3DTileset.fromUrl(
  'http://xxx/tileset.json'
);
viewer.scene.primitives.add(tileset);

// 样式过滤
tileset.style = new Cesium.Cesium3DTileStyle({
  color: {
    conditions: [
      ['${Height} > 50', 'color("red")'],
      ['true', 'color("white")']
    ]
  }
});

// 裁剪(只显示某区域)
tileset.clippingPlanes = new Cesium.ClippingPlaneCollection({
  planes: [new Cesium.ClippingPlane(
    new Cesium.Cartesian3(0, 1, 0), 0
  )],
  edgeWidth: 1.0
});

// 飞到 tileset 范围
viewer.flyTo(tileset);

理解 tileset.json 结构:root → boundingVolume → children → LOD


十、交互 & 拾取

js 复制代码
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction((movement) => {
  const picked = viewer.scene.pick(movement.position);
  if (picked && picked.id) {
    console.log('选中Entity:', picked.id);
  }
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

// 地形拾取(获取点击处笛卡尔坐标)
const ray = viewer.camera.getPickRay(movement.position);
const pos = viewer.scene.globe.pick(ray, viewer.scene);
  • scene.pick() --- 拾取 Entity/Primitive
  • scene.drillPick() --- 拾取多个(穿透)
  • globe.pick(ray, scene) --- 拾取地形表面点

十一、空间分析(进阶)

  • 距离量测Cartesian3.distance(p1, p2)
  • 面积量测:多边形三角剖分累加
  • 通视分析scene.clampToHeight() 或射线检测 Ray + scene.pickFromRay()
  • 剖面分析 :沿线采样 sampleTerrainMostDetailed() 获取高程数组
  • 淹没分析:随时间提高 Polygon 高度 + 样式变化

十二、性能优化(熟练岗必会)

  • 大量静态数据 → Primitive / 专用 Collection,勿用 Entity
  • viewer.scene.requestRenderMode = true 按需渲染
  • 控制 3D Tiles:maximumScreenSpaceError 调大降面数
  • 监听 tileset.tileLoad / tileUnload 做缓存管理
  • 不用的 Entity/Primitive 及时 removedestroy
  • 分批次加载大数据,避免一次塞入
  • compressVertices: true 压缩顶点

十三、自定义效果 & Shader(精通级)

Fabric 自定义材质

js 复制代码
new Cesium.Material({
  fabric: {
    type: 'MyPulse',
    uniforms: { time: 0, color: Cesium.Color.RED },
    source: `
      czm_material czm_getMaterial(czm_materialInput materialInput) {
        czm_material m = czm_defaultMaterial();
        m.diffuse = color.rgb;
        m.alpha = abs(sin(time));
        return m;
      }
    `
  }
});

CustomShader(新版本推荐)

js 复制代码
primitive.customShader = new Cesium.CustomShader({
  uniforms: { u_time: { type: Cesium.UniformType.FLOAT, value: 0 } },
  fragmentShaderText: `
    void fragmentMain(FragmentInput fsInput, inout czm_modelMaterial material) {
      material.diffuse = vec3(sin(u_time)*0.5+0.5, 0.0, 1.0);
    }
  `
});

十四、前端工程化

  • Vitevite-plugin-cesium 自动处理 workers/css
  • Webpack :需 copy Cesium Build 目录中的 WorkersThirdPartyWidgets/widgets.css
  • Vue3:import * as Cesium from 'cesium' + onMounted 初始化
  • React:useEffect 初始化,ref 绑定 container