Skip to content

Image Load 事件 ​

Image Load 事件示例。 图像 events 加载

图像数据源会触发与图像加载相关的事件。你可以监听 imageloadstart、imageloadend 和 imageloaderror 类型的事件来监控图像加载进度。本示例为这些事件注册了监听器,并在地图底部渲染一个图像加载进度条。进度条根据地图的 loadstart 和 loadend 事件进行显示和隐藏。

main.js
js
import Map from 'ol/Map.js';
import View from 'ol/View.js';
import ImageLayer from 'ol/layer/Image.js';
import ImageWMS from 'ol/source/ImageWMS.js';

/**
 * 渲染进度条。
 * @param {HTMLElement} el 目标元素。
 * @class
 */
function Progress(el) {
  this.el = el;
  this.loading = 0;
  this.loaded = 0;
}

/**
 * 增加正在加载的图像计数。
 */
Progress.prototype.addLoading = function () {
  ++this.loading;
  this.update();
};

/**
 * 增加已加载的图像计数。
 */
Progress.prototype.addLoaded = function () {
  ++this.loaded;
  this.update();
};

/**
 * 更新进度条。
 */
Progress.prototype.update = function () {
  const width = ((this.loaded / this.loading) * 100).toFixed(1) + '%';
  this.el.style.width = width;
};

/**
 * 显示进度条。
 */
Progress.prototype.show = function () {
  this.el.style.visibility = 'visible';
};

/**
 * 隐藏进度条。
 */
Progress.prototype.hide = function () {
  const style = this.el.style;
  setTimeout(function () {
    style.visibility = 'hidden';
    style.width = '0px';
  }, 250);
};

const progress = new Progress(document.getElementById('progress'));

const source = new ImageWMS({
  url: 'https://ahocevar.com/geoserver/wms',
  params: {'LAYERS': 'topp:states'},
  serverType: 'geoserver',
});

source.on('imageloadstart', function () {
  progress.addLoading();
});
source.on(['imageloadend', 'imageloaderror'], function () {
  progress.addLoaded();
});

const map = new Map({
  layers: [new ImageLayer({source: source})],
  target: 'map',
  view: new View({
    center: [-10997148, 4569099],
    zoom: 4,
  }),
});

map.on('loadstart', function () {
  progress.show();
});
map.on('loadend', function () {
  progress.hide();
});
index.html
html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Image Load 事件</title>
    <link rel="stylesheet" href="node_modules/ol/ol.css">
    <style>
      .map {
        width: 100%;
        height: 400px;
      }
      .map {
        background: #E0ECED;
      }
      .wrapper {
        position: relative;
      }
      #progress {
        position: absolute;
        bottom: 0;
        left: 0;
        height: 2px;
        background: rgba(0, 60, 136, 0.4);
        width: 0;
        transition: width 250ms;
      }
    </style>
  </head>
  <body>
    <div class="wrapper">
      <div id="map" class="map"></div>
      <div id="progress"></div>
    </div>

    <script type="module" src="main.js"></script>
  </body>
</html>
package.json
json
{
  "name": "image-load-events",
  "dependencies": {
    "ol": "10.11.0"
  },
  "devDependencies": {
    "vite": "^8.1.5"
  },
  "scripts": {
    "start": "vite",
    "build": "vite build"
  }
}