Cesium JS API
AppearanceArcGisMapServerImageryProviderArcGISTiledElevationTerrainProviderArcTypeAssociativeArrayAxisAxisAlignedBoundingBoxbarycentricCoordinatesBillboardBillboardCollectionBillboardGraphicsBillboardVisualizerbinarySearchbinarySearchComparatorBingMapsGeocoderServiceBingMapsImageryProviderBingMapsStyleBlendEquationBlendFunctionBlendingStateBlendOptionBoundingRectangleBoundingSphereBoxEmitterBoxGeometryBoxGeometryUpdaterBoxGraphicsBoxOutlineGeometrybuildModuleUrlCallbackPropertyCameraCameraEventAggregatorCameraEventTypeCartesian2Cartesian3Cartesian4CartographicCartographicGeocoderServiceCatmullRomSplineCesium3DTileCesium3DTileColorBlendModeCesium3DTileContentCesium3DTileFeatureCesium3DTilePointFeatureCesium3DTilesetCesium3DTilesetGraphicsCesium3DTilesetVisualizerCesium3DTileStyleCesium3DTilesVoxelProviderCesiumTerrainProviderCesiumWidgetCheckerboardMaterialPropertyCircleEmitterCircleGeometryCircleOutlineGeometryClassificationPrimitiveClassificationTypeClippingPlaneClippingPlaneCollectionClockClockRangeClockStepcloneCloudCollectionCloudTypeColorColorBlendModeColorGeometryInstanceAttributeColorMaterialPropertycombineComponentDatatypeCompositeEntityCollectionCompositeMaterialPropertyCompositePositionPropertyCompositePropertyCompressedTextureBufferConditionsExpressionConeEmitterConstantPositionPropertyConstantPropertyConstantSplineContextOptionsCoplanarPolygonGeometryCoplanarPolygonOutlineGeometryCornerTypeCorridorGeometryCorridorGeometryUpdaterCorridorGraphicsCorridorOutlineGeometrycreateElevationBandMaterialcreateElevationBandMaterialBandcreateElevationBandMaterialEntrycreateGuidcreateOsmBuildingscreateTangentSpaceDebugPrimitivecreateWorldImagerycreateWorldTerrainCreditCreditDisplayCubicRealPolynomialCullFaceCullingVolumeCumulusCloudCustomDataSourceCustomHeightmapTerrainProviderCustomShaderCustomShaderModeCustomShaderTranslucencyModeCylinderGeometryCylinderGeometryUpdaterCylinderGraphicsCylinderOutlineGeometryCzmlDataSourceDataSourceDataSourceClockDataSourceCollectionDataSourceDisplayDebugAppearanceDebugCameraPrimitiveDebugModelMatrixPrimitiveDefaultProxydefaultValuedefinedDepthFunctiondestroyObjectDeveloperErrorDirectionalLightDirectionUpDiscardEmptyTileImagePolicyDiscardMissingTileImagePolicyDistanceDisplayConditionDistanceDisplayConditionGeometryInstanceAttributeEasingFunctionEllipseGeometryEllipseGeometryUpdaterEllipseGraphicsEllipseOutlineGeometryEllipsoidEllipsoidGeodesicEllipsoidGeometryEllipsoidGeometryUpdaterEllipsoidGraphicsEllipsoidOutlineGeometryEllipsoidRhumbLineEllipsoidSurfaceAppearanceEllipsoidTangentPlaneEllipsoidTerrainProviderEntityEntityClusterEntityCollectionEntityViewEventEventHelperexcludesReverseAxisexportKmlexportKmlModelCallbackexportKmlResultKmlexportKmlResultKmzExpressionExtrapolationTypeFeatureDetectionFogformatErrorFrameRateMonitorFrustumGeometryFrustumOutlineGeometryFullscreenGeocoderServiceGeocodeTypeGeographicProjectionGeographicTilingSchemeGeoJsonDataSourceGeometryGeometryAttributeGeometryAttributesGeometryFactoryGeometryInstanceGeometryInstanceAttributeGeometryPipelineGeometryUpdaterGeometryVisualizergetAbsoluteUrigetBaseUrigetExtensionFromUriGetFeatureInfoFormatgetFilenameFromUrigetImagePixelsgetTimestampGlobeGlobeTranslucencyGoogleEarthEnterpriseImageryProviderGoogleEarthEnterpriseMapsProviderGoogleEarthEnterpriseMetadataGoogleEarthEnterpriseTerrainDataGoogleEarthEnterpriseTerrainProviderGpxDataSourceGregorianDateGridImageryProviderGridMaterialPropertyGroundGeometryUpdaterGroundPolylineGeometryGroundPolylinePrimitiveGroundPrimitiveHeadingPitchRangeHeadingPitchRollHeadingPitchRollValuesHeightmapEncodingHeightmapTerrainDataHeightReferenceHermitePolynomialApproximationHermiteSplineHilbertOrderHorizontalOriginI3SDataProviderI3SFeatureI3SFieldI3SGeometryI3SLayerI3SNodeImageBasedLightingImageMaterialPropertyImageryLayerImageryLayerCollectionImageryLayerFeatureInfoImageryProviderImageryTypesincludesReverseAxisIndexDatatypeIntersectIntersections2DIntersectionTestsIntervalIonIonGeocoderServiceIonImageryProviderIonResourceIonWorldImageryStyleisLeapYearIso8601JulianDateKeyboardEventModifierKmlCameraKmlDataSourceKmlFeatureDataKmlLookAtKmlTourKmlTourFlyToKmlTourWaitLabelLabelCollectionLabelGraphicsLabelStyleLabelVisualizerLagrangePolynomialApproximationLeapSecondLightLightingModelLinearApproximationLinearSplineMapboxImageryProviderMapboxStyleImageryProviderMapMode2DMapProjectionMaterialMaterialAppearanceMaterialSupportMaterialPropertyMathMatrix2Matrix3Matrix4mergeSortmergeSortComparatorMetadataClassMetadataClassPropertyMetadataComponentTypeMetadataEnumMetadataEnumValueMetadataSchemaMetadataTypeModelModelAnimationModelAnimationCollectionModelAnimationLoopModelFeatureModelGraphicsModelNodeModelVisualizerMoonMorphWeightSplineNearFarScalarNeverTileDiscardPolicyNodeTransformationPropertyobjectToQueryOccluderOpenCageGeocoderServiceOpenStreetMapImageryProviderOrientedBoundingBoxOrthographicFrustumOrthographicOffCenterFrustumPackableForInterpolationParticleParticleBurstParticleEmitterParticleSystemPathGraphicsPathVisualizerPeliasGeocoderServicePerInstanceColorAppearancePerspectiveFrustumPerspectiveOffCenterFrustumPinBuilderPixelDatatypePixelFormatPlanePlaneGeometryPlaneGeometryUpdaterPlaneGraphicsPlaneOutlineGeometryPointCloudShadingPointGraphicspointInsideTrianglePointPrimitivePointPrimitiveCollectionPointVisualizerPolygonGeometryPolygonGeometryUpdaterPolygonGraphicsPolygonHierarchyPolygonOutlineGeometryPolylinePolylineArrowMaterialPropertyPolylineCollectionPolylineColorAppearancePolylineDashMaterialPropertyPolylineGeometryPolylineGeometryUpdaterPolylineGlowMaterialPropertyPolylineGraphicsPolylineMaterialAppearancePolylineOutlineMaterialPropertyPolylineVisualizerPolylineVolumeGeometryPolylineVolumeGeometryUpdaterPolylineVolumeGraphicsPolylineVolumeOutlineGeometryPositionPropertyPositionPropertyArrayPostProcessStagePostProcessStageCollectionPostProcessStageCompositePostProcessStageLibraryPostProcessStageSampleModePrimitivePrimitiveCollectionPrimitiveTypePropertyPropertyArrayPropertyBagProxyQuadraticRealPolynomialQuantizedMeshTerrainDataQuarticRealPolynomialQuaternionQuaternionSplinequeryToObjectQueueRayreadyPromiseRectangleRectangleGeometryRectangleGeometryUpdaterRectangleGraphicsRectangleOutlineGeometryReferenceFrameReferencePropertyremoveExtensionRequestRequestErrorEventRequestSchedulerRequestStateRequestTypeResourceRuntimeErrorSampledPositionPropertySampledPropertysampleTerrainsampleTerrainMostDetailedSceneSceneModeSceneTransformsScreenSpaceCameraControllerScreenSpaceEventHandlerScreenSpaceEventTypeshaderDefinesshaderMaximumIntersectionsLengthshaderUniformsShadowMapShadowModeShowGeometryInstanceAttributeSimon1994PlanetaryPositionsSimplePolylineGeometrySingleTileImageryProviderSkyAtmosphereSkyBoxSphereEmitterSphereGeometrySphereOutlineGeometrySphericalSplineSplitDirectionStencilFunctionStencilOperationSteppedSplineStripeMaterialPropertyStripeOrientationStyleExpressionsubdivideArraySunSunLightTaskProcessorTerrainDataTerrainProviderTextureMagnificationFilterTextureMinificationFilterTextureUniformTileAvailabilityTileCoordinatesImageryProviderTileDiscardPolicyTileMapServiceImageryProviderTileProviderErrorTilingSchemeTimeDynamicImageryTimeDynamicPointCloudTimeIntervalTimeIntervalCollectionTimeIntervalCollectionPositionPropertyTimeIntervalCollectionPropertyTimeStandardTransformsTranslationRotationScaleTridiagonalSystemSolverTrustedServersUniformSpecifierUniformTypeUrlTemplateImageryProviderVaryingTypeVelocityOrientationPropertyVelocityVectorPropertyVertexFormatVerticalOriginVideoSynchronizerViewportQuadVisibilityVisualizerVoxelPrimitiveVoxelProviderVoxelShapeTypeVRTheWorldTerrainProviderWallGeometryWallGeometryUpdaterWallGraphicsWallOutlineGeometryWebGLConstantsWebGLOptionsWebMapServiceImageryProviderWebMapTileServiceImageryProviderWebMercatorProjectionWebMercatorTilingSchemeWindingOrderwriteTextToCanvasAnimationAnimationViewModelBaseLayerPickerBaseLayerPickerViewModelCesium3DTilesInspectorCesium3DTilesInspectorViewModelCesiumInspectorCesiumInspectorViewModelClockViewModelCommandcreateCommandFullscreenButtonFullscreenButtonViewModelGeocoderGeocoderViewModelHomeButtonHomeButtonViewModelInfoBoxInfoBoxViewModelNavigationHelpButtonNavigationHelpButtonViewModelPerformanceWatchdogPerformanceWatchdogViewModelProjectionPickerProjectionPickerViewModelProviderViewModelSceneModePickerSceneModePickerViewModelSelectionIndicatorSelectionIndicatorViewModelSvgPathBindingHandlerTimelineToggleButtonViewModelViewerviewerCesium3DTilesInspectorMixinviewerCesiumInspectorMixinviewerDragDropMixinviewerPerformanceWatchdogMixinviewerVoxelInspectorMixinVoxelInspectorVoxelInspectorViewModelVRButtonVRButtonViewModel

Expression

Expression 对象表示在地理空间中的数学运算、逻辑运算和其他特殊计算的表达式。它们可用于自定义图形、渲染效果以及其他操作。表达式是 CesiumJS 中的延续,它使用相同的语言结构。

一个表达式由一个或多个变量名组成,每个变量名对应一个特定的式子部分。变量名可以是一个字符串值,也可以是一个简单的数学运算符(如+-*/),或一个函数(如sincostansqrt等)。表达式可以通过在 CesiumJS 中的代码中使用以及通过 CesiumJS API 调用来实现。

表达式示例

下面是一些可以在 CesiumJS 中使用的示例表达式:

// 变量
var position = "position";
var scale = "scale";

// 简单的数学运算符
var combined = position + "*" + scale;

// 函数
var cosCombined = "cos(" + combined + ")";
var sinCombined = "sin(" + combined + ")";

// 点积
var dotProduct = "dot(" + position + ", " + scale + ")";

//取最大值
var max = "max(" + position + ", " + scale + ")";

// 取最小值
var min = "min(" + position + ", " + scale + ")";

// 向量交叉积
var crossProduct = "cross(" + position + ", " + scale + ")";

变量

变量是表达式的一个重要组成部分。它们代表着特定的式子部分,可以是一个字符串值,也可以是一个数字或向量。定义变量是为了让表达式更有可读性和简洁度。

// 创建一个有位置和比例分量的变量
var position = "position";
var scale = "scale";

// 通过API添加变量
var variables = new Cesium.ExpressionVariables();
variables.add("position", Cesium.Cartesian3.ZERO);
variables.add("scale", 2.0);

// 使用变量并添加到 Cesium 实体中
var material = new Cesium.ColorMaterialProperty(
  new Cesium.Expression("color", "color(" + position + ", " + scale + ")"),
  variables
);
entity.material = material;

在上述示例中,我们定义了两个变量 positionscale,然后用它们来计算一个颜色值。我们还可以使用 Cesium.ExpressionVariables API 包含这些变量以供后续查找。

数学运算符

CesiumJS 支持大部分的数学运算符,包括加减乘除,以及求余。表达式可以用任何个数的操作数来进行运算,并且可以根据需要使用括号控制运算次序。

// 定义数学表达式
var azimuth = Cesium.Math.PI_OVER_TWO - Math.atan2(position.y, position.x);
var distance = Cesium.Cartesian3.magnitude(position);
var direction = new Cesium.Cartesian3(
  Math.cos(azimuth) * distance,
  Math.sin(azimuth) * distance,
  position.z
);

// 将表达式应用于实体材质
var material = new Cesium.ColorMaterialProperty(
  new Cesium.Expression(
    "color",
    "color(" +
      "vec3(" +
      "   (position.x + 1.0) / 2.0," +
      "   (position.y + 1.0) / 2.0," +
      "   (position.z + 1.0) / 2.0" +
      ")," +
      "vec3(" +
      "   direction.x," +
      "   direction.y," +
      "   direction.z" +
      ")" +
      ")"
  )
);

在上述的示例中我们使用一个 + 运算符来生成一个向量 direction,这个向量描述了一个从地球表面的位置 position 开始的方向。distance 是一个用于计算总距离的辅助值,通过使用 Cesium.Cartesian3.magnitude 方法来计算向量的大小。

函数

CesiumJS 提供了大量可用的数学函数来帮助在表达式中进行计算。这些函数可以用括号括起来,与变量一起使用来组成表达式。

// 计算三角函数
var angle = new Cesium.Expression("angle", "atan2(position.y, position.x)");
var sine = new Cesium.Expression("sine", "sin(" + angle + ")");
var cosine = new Cesium.Expression("cosine", "cos(" + angle + ")");

// 计算向量的长度
var length = new Cesium.Expression("length", "length(position)");

// 应用函数结果于对象
var material = new Cesium.ColorMaterialProperty(
  new Cesium.Expression(
    "color",
    "color(min(" + position + ", " + scale + "), max(" + position + "," + scale + "))"
  )
);

在上述示例中,我们使用了 atan2 来计算鼠标的角度,并将其存储在 angle 变量中。然后我们使用了 sincos 函数来计算正弦和余弦。我们还使用了 length 函数来计算向量的长度。

示例

下面是一个使用表达式的简单示例,其中使用了动画帧来改变表达式的值:

// 创建一个表达式
var positionExpression = new Cesium.Expression("position", "vec3(0, time, 0)");

// 将表达式应用于实体属性
var entity = viewer.entities.add({
  position: positionExpression,
  box: {
    dimensions: new Cesium.Cartesian3(10, 20, 30),
    material: Cesium.Color.BLUE,
  },
});

// 设置摄像机视图
viewer.camera.setView({
  destination: new Cesium.Cartesian3(0, 0, 50),
  orientation: {
    heading: Cesium.Math.toRadians(30),
    pitch: Cesium.Math.toRadians(-20),
    roll: Cesium.Math.toRadians(0),
  },
});

// 创建动画帧循环
var frameNumber = 0;
var maxFrameNumber = 600;
var clock = new Cesium.Clock();
clock.onTick.addEventListener(function (clock) {
  frameNumber++;
  if (frameNumber === maxFrameNumber) {
    frameNumber = 0;
  }

  // 更新表达式的值
  positionExpression.evaluate({
    time: (2 * Math.PI * frameNumber) / maxFrameNumber,
  });
});

在上述示例中,我们使用了 vec3 函数来定义位置,根据指定的 time 参数值,表达式每次调用都会返回一个不同的位置点。我们还用这个表达式作为一个实体的位置参数,来操作一个在世界空间中的盒子。最后,我们使用 Cesium.ClockonTick 事件来不断更新表达式的值,并在每帧之后重新渲染场景。