文章目錄
- 一、Cesium 介紹
- 二、 使用
- 1、引入 cesium
- 2、Viewer 配置選項
- 1. 基礎控件配置
- 2. 場景與渲染配置
- 3. 地形配置
- 4. 天空與大氣效果
- 3、坐標系系統
- 3.1 地理坐標系
- 3.2 笛卡爾空間直角坐標系
- 3.3 屏幕坐標系
- 4、Entity 實體
- 4.1 簡介
- 4.2 Entity 常見圖形類型
- Point 點
- Polyline 線
- Polygon 多邊形
- Label 文本
- Billboard 廣告牌
- Model 模型
- 4.3 DataSource 數據源
- GeoJsonDataSource
- KmlDataSource
- CzmlDataSource
- 5、Camera
- 5.1 核心屬性
- 5.2 位置控制方法
- 1. setView(options)
- 2. flyTo(options)
- 3. lookAt(target, offset)
- 5.3 視角控制方法
- 5.4 控制模式
- 5.5 事件
- 6、Scene
- 6.1 常用屬性
- 6.2 常用方法
- 1. pick
- 6.3 事件
一、Cesium 介紹
CesiumJS 是一個開源 JavaScript 庫,用于創建具有最佳性能、精度、視覺質量和易用性的世界級 3D 地球儀和地圖
- 官網: https://cesium.com/
- 官方示例: https://sandcastle.cesium.com/
- API文檔: https://cesium.com/learn/cesiumjs/ref-doc/
- Cesium 中文網: http://cesium.xin/
二、 使用
注:當前使用的是 1.132
版本
1、引入 cesium
兩種方式引入:
- 從 CDN 導入
- 使用 NPM 安裝
(1)使用 CDN,如下示例:
<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><script src="https://cesium.com/downloads/cesiumjs/releases/1.132/Build/Cesium/Cesium.js"></script><link href="https://cesium.com/downloads/cesiumjs/releases/1.132/Build/Cesium/Widgets/widgets.css" rel="stylesheet">
</head>
<body><div id="cesiumContainer"></div><script type="module">Cesium.Ion.defaultAccessToken = 'your_access_token';const viewer = new Cesium.Viewer('cesiumContainer'); </script></div>
</body>
</html>
(2)使用 npm
npm install cesium
使用示例:
import { Viewer } from 'cesium';
import "cesium/Build/Cesium/Widgets/widgets.css";const viewer = new Viewer('cesiumContainer');
2、Viewer 配置選項
new Cesium.Viewer(container, options)
options所有可配選項:Cesium.Viewer.ConstructorOptions
1. 基礎控件配置
-
animation
Boolean,默認 true
控制是否顯示左下角的動畫控件(播放/暫停/時間倍率調整) -
baseLayerPicker
Boolean,默認 true
是否顯示右上角的底圖選擇器(切換影像/地形) -
fullscreenButton
Boolean,默認 true
是否顯示全屏按鈕 -
geocoder
Boolean | Array,默認 true
是否顯示地理編碼搜索框(支持地名搜索) -
homeButton
Boolean,默認 true
是否顯示"返回初始視角"按鈕 -
infoBox
Boolean,默認 true
點擊實體時是否顯示信息框 -
sceneModePicker
Boolean,默認 true
是否顯示場景模式切換按鈕(3D/2D/哥倫布視圖) -
timeline
Boolean,默認 true
是否顯示時間軸控件 -
navigationHelpButton
Boolean,默認 true
是否顯示操作幫助按鈕
2. 場景與渲染配置
-
scene3DOnly
Boolean,默認 false
設為true
時所有幾何體僅以3D模式渲染(節省GPU內存) -
sceneMode
Cesium.SceneMode,默認 SCENE3D
初始場景模式(SCENE2D/SCENE3D/COLUMBUS_VIEW) -
mapProjection
MapProjection,默認 GeographicProjection
2D/哥倫布視圖使用的地圖投影方式 -
shadows
Boolean,默認 false
是否啟用光源陰影 -
terrainShadows
ShadowMode,默認 RECEIVE_ONLY
地形是否投射/接收陰影 -
requestRenderMode
Boolean,默認 false
是否啟用按需渲染模式(減少資源占用)
3. 地形配置
terrainProvider
- 示例:
terrainProvider: await Cesium.createWorldTerrainAsync()
4. 天空與大氣效果
-
skyBox
SkyBox | false
自定義星空背景,設為false
可禁用 -
skyAtmosphere
SkyAtmosphere | false
是否顯示地球大氣層輝光效果
3、坐標系系統
3.1 地理坐標系
Cartographic
- 表示 WGS84 弧度坐標系(經度、緯度、高度,單位為弧度)。
- 使用 Cesium.Cartographic(longitude, latitude, height) 表示,其中經度和緯度為弧度值
- 主要方法:
Cartographic.fromDegrees(longitude, latitude, height)
(角度轉弧度)Cartographic.fromRadians(longitude, latitude, height)
(直接使用弧度)Cartographic.fromCartesian(cartesian3)
(笛卡爾坐標轉地理坐標)
3.2 笛卡爾空間直角坐標系
Cartesian3
- 表示 3D 笛卡爾坐標(x, y, z),原點在地球中心。
- X軸指向本初子午線(經度0°)與赤道(緯度0°)的交點
- Z軸指向北極
- Y軸與X、Z軸構成右手坐標系,指向東經90°與赤道的交點
- 用于三維空間計算,如模型變換、相機控制等
- 通過 Cesium.Cartesian3(x, y, z) 定義
- 主要方法:
Cartesian3.fromDegrees(longitude, latitude, height)
- 經緯度轉笛卡爾坐標
Cesium.Cartesian3.fromDegreesArray(coordinates)
- 返回一個 Cartesian3 位置數組,給定一個以度為單位給出的經度和緯度值數組
Cesium.Cartesian3.fromDegreesArrayHeights(coordinates)
- 返回一個笛卡爾3位置數組,給定經度、緯度和高度值數組,其中經度和緯度以度為單位。
Cartesian3.fromRadians(longitude, latitude, height)
- 弧度轉笛卡爾坐標
Cartesian3.fromElements(x, y, z)
(直接構造)
- 表示 3D 笛卡爾坐標(x, y, z),原點在地球中心。
3.3 屏幕坐標系
- 用于與屏幕交互的 2D 坐標系:
- 原點在畫布左上角
- X軸向右,Y軸向下單位:像素
- 使用 Cartesian2 表示
示例:
const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction((event) => {const screenPosition = event.position; // Cartesian2 類型console.log("點擊屏幕坐標:", screenPosition.x, screenPosition.y);// 轉換為世界坐標const ray = viewer.camera.getPickRay(screenPosition);const cartesian3Position = viewer.scene.globe.pick(ray, viewer.scene); // Cartesian3 類型if (cartesian3Position) {console.log("對應的世界坐標:", cartesian3Position);}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
4、Entity 實體
4.1 簡介
實體實例將多種形式的可視化聚合到單個高級對象中。
它們可以手動創建,并添加到數據源 Viewer#entities
或由數據源生成,例如 CzmlDataSource 和 GeoJsonDataSource 。
entity 配置選項文檔:Entity.html#.ConstructorOptions
Entity 常用方法:
添加 Entity
const entity = viewer.entities.add({ /* 配置 */ });
移除 Entity
viewer.entities.remove(entity);
查找 Entity
const entity = viewer.entities.getById('unique-id');
集合操作
// 移除所有實體
viewer.entities.removeAll();// 顯示/隱藏所有實體
viewer.entities.show = false;
4.2 Entity 常見圖形類型
Point 點
屬性文檔: PointGraphics.html#.ConstructorOptions
示例:
viewer.entities.add({name: "RedPoint",position: Cesium.Cartesian3.fromDegrees(-75, 35),point: {show: true,pixelSize: 30,color: Cesium.Color.RED,},
});
Polyline 線
屬性文檔: PolylineGraphics.html#.ConstructorOptions
示例:
viewer.entities.add({name: "Red line on terrain",polyline: {positions: Cesium.Cartesian3.fromDegreesArray([-75, 35, -125, 35]),width: 5,material: Cesium.Color.RED,},
});
官方示例: Polyline 示例
Polygon 多邊形
屬性文檔: PolygonGraphics.html#.ConstructorOptions
示例:
viewer.entities.add({name: "Red polygon",polygon: {hierarchy: Cesium.Cartesian3.fromDegreesArray([118.12, 24.69, 118.22, 24.69, 118.22, 24.79, 118.12, 24.79]),height: 10,material: Cesium.Color.RED.withAlpha(0.5),outline: true,outlineColor: Cesium.Color.BLUE,},
});
官方示例: Polygon 示例
Label 文本
屬性文檔: LabelGraphics.html#.ConstructorOptions
示例:
viewer.entities.add({position: Cesium.Cartesian3.fromDegrees(-75.1641667, 39.9522222),label: {text: "Philadelphia",font: "24px Helvetica",fillColor: Cesium.Color.SKYBLUE,outlineColor: Cesium.Color.BLACK,outlineWidth: 2,style: Cesium.LabelStyle.FILL_AND_OUTLINE,scale: 2.0,showBackground: true,},
});
Billboard 廣告牌
屬性文檔: BillboardGraphics.html#.ConstructorOptions
示例:
viewer.entities.add({position: Cesium.Cartesian3.fromDegrees(-75.59777, 40.03883),billboard: {show: true,image: "./dist/assets/Cesium_Logo_Color.jpg",scale: 1,width: 100,height: 25,},
});
官方示例: Billboards 示例
Model 模型
Cesium 支持加載多種格式的 3D 模型,包括 glTF/GLB (推薦)、OBJ 等格式
屬性文檔: ModelGraphics.html#.ConstructorOptions
示例:
const entity = viewer.entities.add({name: "air",position: Cesium.Cartesian3.fromDegrees(-123.0744619, 44.0503706),model: {uri: './dist/SampleData/models/CesiumDrone/CesiumDrone.glb',minimumPixelSize: 128,maximumScale: 2000,},
});
viewer.zoomTo(entity);
官方示例: Models 示例
4.3 DataSource 數據源
GeoJsonDataSource
A DataSource 處理 GeoJSON 和 TopoJSON 數據
GeoJSON 介紹: 點擊查看
示例:
viewer.dataSources.add(Cesium.GeoJsonDataSource.load('../../SampleData/ne_10m_us_states.topojson', {stroke: Cesium.Color.HOTPINK,fill: Cesium.Color.PINK,strokeWidth: 3,markerSymbol: '?'})
);
API文檔: GeoJsonDataSource
官方示例: GeoJSON 和 TopoJSON
KmlDataSource
A DataSource 處理 Keyhole Markup Language 2.2 (KML)
KML 標準: https://www.ogc.org/standards/kml/
示例:
viewer.dataSources.add(Cesium.KmlDataSource.load("../SampleData/kml/facilities/facilities.kml",{camera: viewer.scene.camera,canvas: viewer.scene.canvas,},),
);
API文檔: KmlDataSource
官方示例: KML 示例
CzmlDataSource
處理 DataSource CZML。
API文檔: CzmlDataSource
官方示例: CZML Demo
CZML 指南: CZML-Guide
CZML Packet - CZML 文檔/流中存在的標準內容的架構 /czml-writer/wiki/Packet
CZML 是 Cesium 的專有數據格式,具有以下特點:
- 基于 JSON 的文本格式
- 用于描述隨時間變化的場景
- 支持點、線、面、模型、標簽等多種可視化元素
- 支持時間動態屬性(位置、顏色、大小等隨時間變化)
示例:
const czml = [{id: "document",name: "Basic CZML billboard and label",version: "1.0",},{id: "some-unique-id",name: "AGI",billboard: {show: true,image: "./dist/assets/Cesium_Logo_Color.jpg",scale: 1,width: 100,height: 25,},position: {cartesian: [1216361.4096947117, -4736253.175342511, 4081267.4865667094], // },},{id: "some-unique-id2",name: "Label Demo",label: {show: true,text: "Label文本",font: "18px sans-serif",},position: {cartographicDegrees: [-91.17466499519793, 40.31480547471602, 0]},}
]
viewer.dataSources.add(Cesium.CzmlDataSource.load(czml));
5、Camera
官方API: https://cesium.com/learn/cesiumjs/ref-doc/Camera.html
相機由位置、方向和視錐體定義。
作用: 控制場景的觀察視角和位置
5.1 核心屬性
- position: Cartesian3 相機位置
- direction : Cartesian3 相機的觀察方向
- DEFAULT_VIEW_RECTANGLE:創建時相機將查看的默認矩形
示例:
// 獲取相機位置
const position = viewer.camera.position;// 獲取相機方向向量
const direction = viewer.camera.direction;// 設置全局默認視角為中國上空
// 在創建 Viewer 實例之前,設置默認的視圖矩形區域
Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(75.0, // 西經 (West Longitude)0.0, // 南緯 (South Latitude)140.0, // 東經 (East Longitude)60.0 // 北緯 (North Latitude)
);
const viewer = new Cesium.Viewer("cesiumContainer");
5.2 位置控制方法
1. setView(options)
設置相機位置、方向和變換。
options屬性:
- destination 攝像機在世界坐標中的最終位置或從自上而下視圖可見的矩形。
- orientation 包含方向和向上屬性或航向、俯仰和滾動屬性的對象。默認情況下,方向在 3D 視圖中指向幀的中心,在哥倫布視圖中指向負 z 方向。向上方向將在 3D 中指向當地北方,在哥倫布視圖中指向正 y 方向。在無限滾動模式下,在 2D 中不使用方向
- endTransform
- convert
示例1:
viewer.camera.setView({destination : Cesium.Cartesian3.fromDegrees(-117.16, 32.71, 15000.0)
});
示例2:
viewer.camera.setView({destination: Cesium.Cartesian3.fromDegrees(116.39, 39.91, 10000.0),orientation: {heading: Cesium.Math.toRadians(0.0), // 偏航角pitch: Cesium.Math.toRadians(-90.0), // 俯仰角roll: 0.0 // 翻滾角}
});
2. flyTo(options)
將相機從當前位置飛行到新位置。
options:
- destination 攝像機在世界坐標中的最終位置
- orientation 包含方向和向上屬性或航向、俯仰和滾動屬性的對象
- duration 飛行持續時間(以秒為單位)
- complete 完成時要執行的函數
- cancel 取消時要執行的函數
示例:
viewer.camera.flyTo({destination: Cesium.Cartesian3.fromDegrees(116.39, 39.91, 2000.0),duration: 3.0, // 飛行時間(秒)complete: function() {console.log('飛行完成');}
});
3. lookAt(target, offset)
使用目標和偏移設置相機位置和方向。目標必須以世界坐標給出
name | type | 描述 |
---|---|---|
target | Cartesian3 | 世界坐標中的目標位置 |
offset | Cartesian3|HeadingPitchRange | 以目標為中心的局部東西向上參考系中與目標的偏移量。 |
示例:
viewer.camera.lookAt(Cesium.Cartesian3.fromDegrees(116.39, 39.91, 1000.0), // 目標點new Cesium.HeadingPitchRange(0.0, -1.57, 1000.0) // 相對偏移
);
5.3 視角控制方法
1. 旋轉相機:
注: angle:旋轉的角度,以弧度為單位
viewer.camera.rotate(axis, angle); // 繞軸旋轉
viewer.camera.rotateUp(angle); // 向上旋轉
viewer.camera.rotateDown(angle); // 向下旋轉
viewer.camera.rotateLeft(angle); // 向左旋轉
viewer.camera.rotateRight(angle); // 向右旋轉
2. 移動相機
注: amount: 移動的量,以米為單位
viewer.camera.move(direction, amount); // 沿方向移動
viewer.camera.moveForward(amount); // 向前移動
viewer.camera.moveBackward(amount); // 向后移動
viewer.camera.moveUp(amount); // 向上移動
viewer.camera.moveDown(amount); // 向下移動
viewer.camera.moveLeft(amount); // 向左移動
viewer.camera.moveRight(amount); // 向右移動
3. 縮放
注: amount: 移動的量,以米為單位
viewer.camera.zoomIn(amount); // 放大
viewer.camera.zoomOut(amount); // 縮小
5.4 控制模式
// 獲取相機控制器
const controller = viewer.scene.screenSpaceCameraController;// 配置控制參數
controller.enableRotate = true; // 允許旋轉
controller.enableTranslate = true; // 允許平移
controller.enableZoom = true; // 允許縮放
controller.enableTilt = true; // 允許傾斜
controller.enableLook = true; // 允許環視// 靈敏度設置
controller.zoomFactor = 2.0; // 縮放靈敏度
controller.rotateFactor = 1.0; // 旋轉靈敏度
5.5 事件
// 相機移動事件
viewer.camera.moveStart.addEventListener(function() {console.log('相機開始移動');
});viewer.camera.moveEnd.addEventListener(function() {console.log('相機移動結束');
});
6、Scene
Cesium 場景中所有3D圖形對象和狀態的容器。通常,場景不是直接創建的;而是由CesiumWidget隱式創建。
官方API: https://cesium.com/learn/cesiumjs/ref-doc/Scene.html
Scene 的作用:
- 管理場景中所有可視化對象(實體、圖元、數據源等)
- 控制渲染流程和渲染狀態
- 處理場景的視覺效果(光照、霧、大氣等)
- 管理相機和視圖變換
Scene 的層級結構:
// Scene 包含的主要組件
const scene = viewer.scene;
const globe = scene.globe; // 地球對象
const camera = scene.camera; // 相機對象
const primitives = scene.primitives; // 圖元集合
const groundPrimitives = scene.groundPrimitives; // 地面圖元集合
6.1 常用屬性
場景模式屬性:
// 場景模式
scene.mode = Cesium.SceneMode.SCENE3D; // 3D模式
// scene.mode = Cesium.SceneMode.SCENE2D; // 2D模式
// scene.mode = Cesium.SceneMode.COLUMBUS_VIEW; // 哥倫布視圖
globe(地球)
文檔: Globe
示例:
viewer.scene.globe.show = false
Primitives(圖元)
文檔: PrimitiveCollection
示例:
viewer.scene.primitives.add(primitive); // 添加圖元
scene.primitives.remove(primitive); // 移除圖元
scene.primitives.removeAll(); // 移除所有圖元
scene.primitives.lowerToBottom(primitive); // 移動到底層
scene.primitives.raiseToTop(primitive); // 移動到頂層
6.2 常用方法
1. pick
pick (windowPosition, width , height )
返回具有’ primitive’屬性的對象,該對象包含場景中的第一個(頂部)基本體在特定的窗口坐標處
示例:
const handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
handler.setInputAction(function(movement) {const feature = scene.pick(movement.endPosition);console.log('feature', feature)
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
對比 drillPick
:
pick :方法只返回鼠標位置最頂層的可見對象;如果多個對象重疊,只返回最上面的一個
drillPick:方法返回鼠標位置的所有對象(從頂層到底層);適合需要選擇多個重疊對象的場景
6.3 事件
postRender
獲取將在渲染場景后立即引發的事件。
活動訂閱者接收Scene實例作為第一個參數,并接收當前時間作為第二個參數。
preRender
獲取在場景更新之后以及場景渲染之前立即引發的事件。
事件的訂閱者將Scene實例作為第一個參數,將當前時間作為第二個參數參數。
preUpdate
獲取在更新或渲染場景之前將引發的事件。
活動訂閱者接收Scene實例作為第一個參數,并接收當前時間作為第二個參數。
示例:
// 預渲染事件
scene.preRender.addEventListener(function(scene, time) {// 每幀渲染前執行console.log('預渲染:', scene);
});// 渲染后事件
scene.postRender.addEventListener(function(scene, time) {// 每幀渲染后執行console.log('渲染完成:', scene);
});