原文链接及内容

图像数据源触发与图像加载相关的事件。您可以监听imageloadstart
、imageloadend
和imageloaderror
类型的事件来监控图像的加载进度。本例为这些事件注册侦听器,并在地图底部渲染图像加载进度条,进度条根据地图的loadstart和loadend事件显示和隐藏。
main.js
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
| import ImageLayer from 'ol/layer/Image.js'; import ImageWMS from 'ol/source/ImageWMS.js'; import Map from 'ol/Map.js'; import View from 'ol/View.js';
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 = 0; }, 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
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Image Load Events</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 src="https://cdn.jsdelivr.net/npm/elm-pep@1.0.6/dist/elm-pep.js"></script> <script type="module" src="main.js"></script> </body> </html>
|