Cesium(四)常用代码总结

1、阴影效果
viewer.shadows = true;

2、取消左键双击事件
viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);

3、定位飞到某处
viewer.scene.camera.flyTo({ destination: rectangle });

4、开启灯光
scene.globe.enableLighting = true;

5、限制缩放距离
scene.screenSpaceCameraController.minimumZoomDistance = 100;

6、解决Cesium绘制几何图形被高程遮挡问题
viewer.scene.globe.depthTestAgainstTerrain = true;

7、point贴地
 var point = viewer.entities.add({
                position: worldPosition,
                point: {
                    pixelSize: 10,
                    color: Cesium.Color.YELLOW,
                    //控制是否贴地
                    heightReference: Cesium.HeightReference.CLAMP_TO_GROUND
                },
            });

8、地球移动事件
camera.moveStart.addEventListener(function() {
});
 camera.moveEnd.addEventListener(function() {
});

9、取消Cesium版权信息
$(".cesium-widget-credits").remove();

10、自定义BaseLayerPicker
         var esriMap = new Cesium.ArcGisMapServerImageryProvider({
            url:'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer',
            enablePickFeatures:false
        });
        //设置ProviderViewModel:
        var esriMapModel = new Cesium.ProviderViewModel({
            name:'esri Maps',
            iconUrl:Cesium.buildModuleUrl('./Widgets/Images/ImageryProviders/esriWorldImagery.png'),
            tooltip:'ArcGIS 地图服务',
            creationFunction:function () {
                return esriMap;
            }
        });
        //只有一个
        var providerViewModels = [];
        providerViewModels.push(esriMapModel);
        viewer.baseLayerPicker.viewModel.imageryProviderViewModels = providerViewModels;

11、设置时间
// 设置时钟和时间线
viewer.clock.shouldAnimate = true; // 当viewer开启后,启动动画
viewer.clock.startTime = Cesium.JulianDate.fromIso8601("2017-07-11T16:00:00Z");
viewer.clock.stopTime = Cesium.JulianDate.fromIso8601("2017-07-11T16:20:00Z");
viewer.clock.currentTime = Cesium.JulianDate.fromIso8601("2017-07-11T16:00:00Z");
viewer.clock.multiplier = 2; // 设置加速倍率
viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK_MULTIPLIER; // tick computation mode(还没理解具体含义)
viewer.clock.clockRange = Cesium.ClockRange.LOOP_STOP; // 循环播放
viewer.timeline.zoomTo(viewer.clock.startTime, viewer.clock.stopTime); // 设置时间的可见范围

12、拾取
/**
 * 返回对应窗口位置最上面一个Entity 如果该位置没有对象那么返回undefined
 * @param {Cartesian2} windowPosition 窗口坐标
 * @returns {Entity} 返回值
 */
function pickEntity(viewer, windowPosition) {
  var picked = viewer.scene.pick(windowPosition);
  if (defined(picked)) {
    var id = Cesium.defaultValue(picked.id, picked.primitive.id);
    if (id instanceof Cesium.Entity) {
      return id;
    }
  }
  return undefined;
};

/**
 *返回对应窗口位置所有Entity的列表 如果该位置没有对象那么返回undefined
 * 返回值按可视化顺序从前到后存储在数组里
 *
 * @param {Cartesian2} windowPosition 窗口位置
 * @returns {Entity[]}  
 */
function drillPickEntities(viewer, windowPosition) {
  var i;
  var entity;
  var picked;
  var pickedPrimitives = viewer.scene.drillPick(windowPosition);
  var length = pickedPrimitives.length;
  var result = [];
  var hash = {};

  for (i = 0; i < length; i++) {
    picked = pickedPrimitives[i];
    entity = Cesium.defaultValue(picked.id, picked.primitive.id);
    if (entity instanceof Cesium.Entity &&
        !Cesium.defined(hash[entity.id])) {
      result.push(entity);
      hash[entity.id] = true;
    }
  }
  return result;
};
该代码出自:https://www.jianshu.com/p/8ae3624347cb
13、检测深度
//为false时,没有高程遮挡效果
viewer.scene.globe.depthTestAgainstTerrain = false;
//为true时,有高程遮挡效果
viewer.scene.globe.depthTestAgainstTerrain = true;

14、加载geoserver的WMS服务

    var provider = new Cesium.WebMapServiceImageryProvider({
              url: 'http://localhost:8080/geoserver/cite/wms',
              layers: 'cite:city',
              parameters: {
              	   service : 'WMS',
                  format: 'image/png',
                  transparent: true,
              }
          });
    viewer.imageryLayers.addImageryProvider(provider);

15、自定义credit


var viewer = new Cesium.Viewer('cesiumContainer');
var credit = new Cesium.Credit('Title', '../images/facility.gif', 'http://www.cesiumjs.org');

viewer.scene.frameState.creditDisplay.addDefaultCredit(credit)

16、拾取

    Scene.pick : 返回窗口坐标对应的图元的第一个对象。
    Scene.drillPick :返回窗口坐标对应的所有对象列表。
    Globe.pick : 返回一条射线和地形的相交位置点。

17、禁止缩放

viewer.scene.screenSpaceCameraController.enableZoom = false;

18、控制时钟暂停与继续

  pauseOrContinue (state) {
    this.viewer.clock.shouldAnimate = state
  }

19、绕点飞行

var viewer = new Cesium.Viewer('cesiumContainer');
   var options = {
           
                lng: 117.1423291616,
                 lat: 39.0645831633,
                 height: 15.8,
                 heading: 0.0,
                 pitch: 0.0,
                roll: 0.0
             };
var position = Cesium.Cartesian3.fromDegrees(options.lng, options.lat, options.height);
// 相机看点的角度,如果大于0那么则是从地底往上看,所以要为负值,这里取-30度
    var pitch = Cesium.Math.toRadians(-30);
    // 给定飞行一周所需时间,比如10s, 那么每秒转动度数
    var angle = 360 / 30;
    // 给定相机距离点多少距离飞行,这里取值为5000m
    var distance = 5000;
    var startTime = Cesium.JulianDate.fromDate(new Date());
    
   // var stopTime = Cesium.JulianDate.addSeconds(startTime, 10, new Cesium.JulianDate());
 
    viewer.clock.startTime = startTime.clone();  // 开始时间
   // viewer.clock.stopTime = stopTime.clone();     // 结速时间
    viewer.clock.currentTime = startTime.clone(); // 当前时间
    viewer.clock.clockRange = Cesium.ClockRange.CLAMPED; // 行为方式
    viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK; // 时钟设置为当前系统时间; 忽略所有其他设置。
    // 相机的当前heading
    var initialHeading = viewer.camera.heading;
    var Exection = function TimeExecution() {
            // 当前已经过去的时间,单位s
            var delTime = Cesium.JulianDate.secondsDifference(viewer.clock.currentTime, viewer.clock.startTime);
            var heading = Cesium.Math.toRadians(delTime * angle) + initialHeading;
            viewer.scene.camera.setView({
                destination :position, // 点的坐标
                orientation:{
                    heading: heading,
                    pitch : pitch,
 
                }
            });
            viewer.scene.camera.moveBackward(distance);
                  
       if (Cesium.JulianDate.compare(viewer.clock.currentTime, viewer.clock.stopTime) >= 0) {
                viewer.clock.onTick.removeEventListener(Exection);
            }
    };

20、只让地球显示一块区域,其余裁剪

var coffeeBeltRectangle = Cesium.Rectangle.fromDegrees(-180.0, -23.43687, 180.0, 23.43687);

viewer.scene.globe.cartographicLimitRectangle = coffeeBeltRectangle;

21、关闭HDR

viewer.scene.highDynamicRange = false;

22、防止进入地下
Cesium(四)常用代码总结_第1张图片23、billboard显示不完整怎么解决?
在这里插入图片描述
24、gltf模型双面渲染
doubleSided改为true
Cesium(四)常用代码总结_第2张图片
25、开启debugShowFramesPerSecond
在这里插入图片描述

scene.debugShowFramesPerSecond = true;

26、监听entity选择改变代码示例

var lastSelectedPin;
viewer.selectedEntityChanged.addEventListener(function(newEntity) {
    if (lastSelectedPin && lastSelectedPin.billboard) {
        lastSelectedPin.billboard.show = false;
    }
    lastSelectedPin = newEntity;
    if (lastSelectedPin && lastSelectedPin.billboard) {
        lastSelectedPin.billboard.show = true;
    }
});

27、局部坐标系

    //以点为原点建立局部坐标系(东方向为x轴,北方向为y轴,垂直于地面为z轴),得到一个局部坐标到世界坐标转换的变换矩阵
    var localToWorld_Matrix = Cesium.Transforms.eastNorthUpToFixedFrame(position);

28、显示与隐藏cesium的控件

viewer.homeButton.container.childNodes[1].style.display = "none"

29、判断是否在可视范围内

var cullingVolume = frameState.cullingVolume;
var boundingVolume = defaultValue(surfaceTile.orientedBoundingBox, surfaceTile.boundingSphere3D);
var intersection = cullingVolume.computeVisibility(boundingVolume);

30、计算一个图元的法向量

        var geometry = GeometryPipeline.computeNormal(new Geometry({
            attributes: attributes,
            indices: indices,
            primitiveType: PrimitiveType.TRIANGLES,
            boundingSphere: boundingSphere
        }));

31、图元生成线框形式

var instance = new Cesium.GeometryInstance({
  geometry : Cesium.GeometryPipeline.toWireframe(new Cesium.TetrahedronGeometry()),
  modelMatrix : modelMatrix,
  attributes : {
    color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.WHITE)
  }
});

你可能感兴趣的:(Ceisum)