原文链接及内容

运行界面

这个例子使用“即时”渲染API,在地理坐标中渲染几何图形。即时渲染API允许绘制已设置样式的几何图形,而无需首先将这些几何要素添加到图层中。使用getVectorContext函数从一个渲染事件创建一个渲染上下文,通过使用渲染上下文的context.drawgeometry()context.setstyle()方法,便可以在每个渲染帧上绘制任何几何图形。在本例中使用了useGeographic函数,以便几何图形可以用地理坐标表示。

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
import Stamen from 'ol/source/Stamen.js';
import TileLayer from 'ol/layer/Tile.js';
import {Circle, Fill, Style} from 'ol/style.js';
import {Map, View} from 'ol/index.js';
import {Point} from 'ol/geom.js';
import {getVectorContext} from 'ol/render.js';
import {upAndDown} from 'ol/easing.js';
import {useGeographic} from 'ol/proj.js';

useGeographic();

const layer = new TileLayer({
source: new Stamen({
layer: 'toner',
}),
});

const map = new Map({
layers: [layer],
target: 'map',
view: new View({
center: [0, 0],
zoom: 2,
}),
});

const image = new Circle({
radius: 8,
fill: new Fill({color: 'rgb(255, 153, 0)'}),
});

const style = new Style({
image: image,
});

const n = 1000;
const geometries = new Array(n);

for (let i = 0; i < n; ++i) {
const lon = 360 * Math.random() - 180;
const lat = 180 * Math.random() - 90;
geometries[i] = new Point([lon, lat]);
}

layer.on('postrender', function (event) {
const vectorContext = getVectorContext(event);

for (let i = 0; i < n; ++i) {
const importance = upAndDown(Math.pow((n - i) / n, 0.15));
if (importance < 0.1) {
continue;
}
image.setOpacity(importance);
image.setScale(importance);
vectorContext.setStyle(style);
vectorContext.drawGeometry(geometries[i]);
}

const lon = 360 * Math.random() - 180;
const lat = 180 * Math.random() - 90;
geometries.push(new Point([lon, lat]));
geometries.shift();
map.render();
});

界面布局文件index.html代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Immediate Rendering (Geographic)</title>
<link rel="stylesheet" href="node_modules/ol/ol.css">
<style>
.map {
width: 100%;
height: 400px;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<!-- Pointer events polyfill for old browsers, see https://caniuse.com/#feat=pointer -->
<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>