Openlayers示例4 | Animated GIF

Animated GIF

使用GIF动画作为图标的例子。动画是使用Gifler库实现的。

<!DOCTYPE html>
<html lang="zn">

<head>
  <meta charset="UTF-8">
  <!-- 引入OpenLayers CSS样式 -->
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.13.0/css/ol.css"
    type="text/css">
  <!-- 引入OpenLayers JS库 -->
  <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.13.0/build/ol.js"></script>
  <!-- 引入gifler JS库 -->
  <script src="https://unpkg.com/gifler@0.1.0/gifler.min.js"></script>
  <!-- https://themadcreator.github.io/gifler/ -->
  <!-- css代码 -->
  <style type="text/css">
    .map {
      width: 100%;
      height: 600px;
    }
  </style>
  </style>
  <title>Animated GIF</title>
</head>
<body>
  <div id="map" class="map"></div>
</body>
<script>
  // 定义一个点,用于显示图标的位置
  const iconFeature = new ol.Feature({
    geometry: new ol.geom.Point(ol.proj.fromLonLat([116.28, 39.54])),
  });
  // 定义一个点的矢量资源
  const vectorSource = new ol.source.Vector({
    features: [iconFeature],
  });
  const vectorLayer = new ol.layer.Vector({
    source: vectorSource,
  });

  // 定义光栅图层
  const rasterLayer = new ol.layer.Tile({
    source: new ol.source.Stamen({
      layer: 'toner',
    }),
  });
  // 初始化图层
  const map = new ol.Map({
    // 添加图层
    layers: [rasterLayer, vectorLayer],
    // 绑定页面元素
    target: document.getElementById('map'),
    // 设置视图,ol.proj.fromLonLat([116.28, 39.54])是大概是北京经纬度
    view: new ol.View({
      center: ol.proj.fromLonLat([116.28, 39.54]),
      zoom: 2,
    }),
  });
  // gif动态图的url链接
  const gifUrl = 'https://openlayers.org/en/latest/examples/data/globe.gif';
  // 使用Gifler将链接转化为gif图片
  const gif = gifler(gifUrl);
  gif.frames(
    document.createElement('canvas'),
    function (ctx, frame) {
      if (!iconFeature.getStyle()) {
        iconFeature.setStyle(
          new ol.style.Style({
            image: new ol.style.Icon({
              img: ctx.canvas,
              imgSize: [frame.width, frame.height],
              opacity: 0.8,
            }),
          })
        );
      }
      ctx.clearRect(0, 0, frame.width, frame.height);
      ctx.drawImage(frame.buffer, frame.x, frame.y);
      map.render();
    },
    true
  );

  // 改变鼠标经过gif图标时的光标样式为pointer
  map.on('pointermove', function (e) {
    // 获取相对于map的位置的像素点坐标
    const pixel = map.getEventPixel(e.originalEvent);
    // 判断像素点坐标是否有Feature要素,返回boolean
    const hit = map.hasFeatureAtPixel(pixel);
    map.getTarget().style.cursor = hit ? 'pointer' : '';
  });
</script>
</html>
posted @ 2022-03-20 13:29  槑孒  阅读(321)  评论(0编辑  收藏  举报