cesium gif广告牌

cesium 并不能直接通过BillboardGraphics类播放gif动画,需要借助第三方库,解析gif每帧动画,动态修改BillboardGraphics类的image属性实现。通过对几种解析gif动画库的比较,这里推荐使用gifler.js。

1 引入第三方库

这里推荐直接通过script 标签的方式引入使用,在开发过程中,发现通过npm 方式引入部分版本存在问题。

<script type="text/javascript" src="./static/libs/gifler.min.js"></script>

2 GifMarker 类封装

GifMarker.js

/*
 * @Description: 
 * @Author: maizi
 * @Date: 2023-04-11 10:57:16
 * @LastEditTime: 2024-07-23 14:42:48
 * @LastEditors: maizi
 */

class GifMarker {
  constructor(viewer, coords, options = {}) {
    this.viewer = viewer;
    this.coords = coords;
    this.options = options;
    this.props = this.options.props;
    this.baseHeight =  this.coords[2] || 0;
    this.entity = null;
    this.init();
  }

  init() {
    this.entity = new Cesium.Entity({
      type: "gif_point",
      position: Cesium.Cartesian3.fromDegrees(this.coords[0], this.coords[1], this.baseHeight),
      props: this.props,
      billboard: {
        scale: 0.4,
        color: new Cesium.Color(1, 1, 1),
        disableDepthTestDistance: Number.POSITIVE_INFINITY,
      },
    });
    const gifPicture  = require('@/assets/img/globe.gif')
    const canvas = document.createElement('canvas');
    const giflerObj =  gifler(gifPicture)
   
    giflerObj.frames(canvas, (ctx, frame)=> {
      this.entity.billboard.image = new Cesium.CallbackProperty(() => {
        return frame.buffer.toDataURL()
      }, false);
    })
  }

  setSelect(enabled) {
    if (enabled) {
      this.addPoint()
    } else {
      this.removePoint()
    }
  }

  addPoint() {
    this.point = new Cesium.Entity({
      position: Cesium.Cartesian3.fromDegrees(this.coords[0], this.coords[1],  this.baseHeight),
      point: {
        color: Cesium.Color.DARKBLUE.withAlpha(.4),
        pixelSize: 6,
        outlineColor: Cesium.Color.YELLOW.withAlpha(.8),
        outlineWidth: 4,
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      }     
    }); 
    this.viewer.entities.add(this.point)
  }

  removePoint() {
    if (this.point) {
      this.viewer.entities.remove(this.point)
      this.point = null
    }
  }

}

export {
  GifMarker
}

3 完整示例代码

MapWorks.js


import { GifMarker } from './GifMarker'
// 初始视图定位在中国
Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(90, -20, 110, 90);
//天地图key
const key = '39673271636382067f0b0937ab9a9677'
let viewer = null;
let eventHandler = null;
let gifLayer = null
let gifList = []
let selectGraphic = null

function initMap(container) {
  viewer = new Cesium.Viewer(container, {
    animation: false,
    baseLayerPicker: false,
    fullscreenButton: false,
    geocoder: false,
    homeButton: false,
    infoBox: false,
    sceneModePicker: false,
    selectionIndicator: false,
    timeline: false,
    navigationHelpButton: false, 
    scene3DOnly: true,
    orderIndependentTranslucency: false,
    contextOptions: {
      webgl: {
        alpha: true
      }
    }
  })
  viewer._cesiumWidget._creditContainer.style.display = 'none'
  viewer.scene.fxaa = true
  viewer.scene.postProcessStages.fxaa.enabled = true
  if (Cesium.FeatureDetection.supportsImageRenderingPixelated()) {
    // 判断是否支持图像渲染像素化处理
    viewer.resolutionScale = window.devicePixelRatio
  }
  // 移除默认影像
  removeAll()
  // 地形深度测试
  viewer.scene.globe.depthTestAgainstTerrain = true
  // 背景色
  viewer.scene.globe.baseColor = new Cesium.Color(0.0, 0.0, 0.0, 0)
  // 太阳光照
  viewer.scene.globe.enableLighting = true;

  // 初始化图层
  initLayer()
  // 鼠标事件
  initClickEvent()

  //调试
  window.viewer = viewer
}
function initClickEvent() {
  eventHandler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
  initLeftClickEvent()
  initMouseMoveEvent()
}

function initLeftClickEvent() {
  eventHandler.setInputAction((e) => {
    if (selectGraphic) {
      selectGraphic.setSelect(false)
      selectGraphic = null
    }
    let pickedObj = viewer.scene.pick(e.position);
    if (pickedObj && pickedObj.id) {
      if (pickedObj.id.type === 'gif_point') {
        selectGraphic = getGraphicById(pickedObj.id.id)
        if (selectGraphic) {
          selectGraphic.setSelect(true)
        }
      }
    }
  },Cesium.ScreenSpaceEventType.LEFT_CLICK)
}

function initMouseMoveEvent() {
  eventHandler.setInputAction((e) => {
    const pickedObj = viewer.scene.pick(e.endPosition);
    if (pickedObj && pickedObj.id) {
      if (pickedObj.id.type === 'gif_point') {
        // 改变鼠标状态
        viewer._element.style.cursor = "";
        document.body.style.cursor = "pointer";
      } else {
        viewer._element.style.cursor = "";
        document.body.style.cursor = "default";
      }
    } else {
      viewer._element.style.cursor = "";
      document.body.style.cursor = "default";
    }
  },Cesium.ScreenSpaceEventType.MOUSE_MOVE)
}

function getGraphicById(id) {
  let graphic = null
  for (let i = 0; i < gifList.length; i++) {
    if (gifList[i].entity.id === id) {
      graphic = gifList[i]
      break
    } 
  }
  return graphic
}

function addTdtLayer(options) {
  let url = `https://t{s}.tianditu.gov.cn/DataServer?T=${options.type}&x={x}&y={y}&l={z}&tk=${key}`
  const layerProvider = new Cesium.UrlTemplateImageryProvider({
    url: url,
    subdomains: ['0','1','2','3','4','5','6','7'],
    tilingScheme: new Cesium.WebMercatorTilingScheme(),
    maximumLevel: 18
  });
  viewer.imageryLayers.addImageryProvider(layerProvider);
}


function initLayer() {
  addTdtLayer({
    type: 'img_w'
  })
  addTdtLayer({
    type: 'cia_w'
  })
  gifLayer = new Cesium.CustomDataSource('gifMarker')
  viewer.dataSources.add(gifLayer)
  viewer.scene.camera.flyTo({
    destination: {
      x: -1336054.4941524172,
      y: 5328287.0808220925,
      z: 3232509.529188942
    },
    orientation: {
      heading: 6.174535958701296,
      pitch: -0.695984291307258,
      roll: 0,
    }
  });
}

function loadGifMarker(points) {
  points.forEach(item => {
    const gifMarker = new GifMarker(viewer, item)
    gifList.push(gifMarker)
    gifLayer.entities.add(gifMarker.entity)
  });
}


function removeAll() {
  viewer.imageryLayers.removeAll();
}

function destroy() {
  viewer.entities.removeAll();
  viewer.imageryLayers.removeAll();
  viewer.destroy();
}

export {
  initMap,
  loadGifMarker,
  destroy
}

GifMarker.vue

<!--
 * @Description: 
 * @Author: maizi
 * @Date: 2023-04-07 17:03:50
 * @LastEditTime: 2023-04-11 13:48:01
 * @LastEditors: maizi
-->

<template>
  <div id="container">
  </div>
</template>

<script>
import * as MapWorks from './js/MapWorks'
export default {
  name: 'GifMarker',
  mounted() {
    this.init();
  },
  methods:{
    init(){
      let container = document.getElementById("container");
      MapWorks.initMap(container)
      //创建gif点
      let points = [
        [104.074822, 30.659807, 60],
        [104.076822, 30.653807, 60],
        [104.075822, 30.652807, 60],
        [104.072822, 30.654807, 60]
      ];
      MapWorks.loadGifMarker(points)
    }
  },

  beforeDestroy(){
    //实例被销毁前调用,页面关闭、路由跳转、v-if和改变key值
    MapWorks.destroy();
  }
}
</script>

<style lang="scss" scoped>
#container{
  width: 100%;
  height: 100%;
  background: rgba(7, 12, 19, 1);
  overflow: hidden;
  background-size: 40px 40px, 40px 40px;
  background-image: linear-gradient(hsla(0, 0%, 100%, 0.05) 1px, transparent 0), linear-gradient(90deg, hsla(0, 0%, 100%, 0.05) 1px, transparent 0);
}


</style>

4 运行结果

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Cesium中添加广告牌可以通过创建一个实体对象,并在其中设置广告牌的位置和显示属性。以下是几种不同的方法来添加广告牌: 方法一:设置广告牌的位置和高度 ```javascript let bill = new Cesium.Entity({ position: new Cesium.Cartesian3.fromDegrees(经度, 纬度, 高度), billboard: { image: "./img/laboratory.png", } }); ``` 这种方法可以通过设置广告牌的位置和高度来完全显示在地面上。 方法二:只设置广告牌的位置 ```javascript let bill = new Cesium.Entity({ position: new Cesium.Cartesian3.fromDegrees(经度, 纬度), billboard: { image: "./img/laboratory.png", } }); ``` 这种方法只设置广告牌的位置,没有设置高度属性,广告牌可能只显示在地面的一部分。 方法三:只设置广告牌的位置 ```javascript let bill = new Cesium.Entity({ position: new Cesium.Cartesian3.fromDegrees(经度, 纬度), }); ``` 这种方法只设置广告牌的位置,没有设置广告牌的显示属性,需要根据实际需求进行进一步设置。 以上是在Cesium中添加广告牌的几种方法,根据实际需求选择适合的方法进行设置。 #### 引用[.reference_title] - *1* *2* *3* [Cesium加载广告牌(一)](https://blog.csdn.net/ekcchina/article/details/130280593)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insertT0,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值