原文链接及内容

运行界面

这个例子创建了一个CanvasGradient。矢量数据从文件中加载,并给各个要素填充了渐变色。同样的技术也可以用于CanvasPattern

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
import KML from 'ol/format/KML.js';
import Map from 'ol/Map.js';
import VectorLayer from 'ol/layer/Vector.js';
import VectorSource from 'ol/source/Vector.js';
import View from 'ol/View.js';
import {DEVICE_PIXEL_RATIO} from 'ol/has.js';
import {fromLonLat} from 'ol/proj.js';

// Gradient and pattern are in canvas pixel space, so we adjust for the
// renderer's pixel ratio
// 渐变和图案都存在于Canvas的像素空间,因此我们只需调整渲染器的像素比例
const pixelRatio = DEVICE_PIXEL_RATIO;

// Generate a rainbow gradient
// 生成一个彩虹风格的渐变
const canvas = document.createElement('canvas');
const context = canvas.getContext('2d');
const gradient = context.createLinearGradient(0, 0, 1024 * pixelRatio, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1 / 6, 'orange');
gradient.addColorStop(2 / 6, 'yellow');
gradient.addColorStop(3 / 6, 'green');
gradient.addColorStop(4 / 6, 'aqua');
gradient.addColorStop(5 / 6, 'blue');
gradient.addColorStop(1, 'purple');

const vectorLayer = new VectorLayer({
background: 'white',
source: new VectorSource({
url: 'data/kml/states.kml',
format: new KML({extractStyles: false}),
}),
style: {
'fill-color': gradient,
'stroke-width': 1,
'stroke-color': '#333',
},
});

const map = new Map({
layers: [vectorLayer],
target: 'map',
view: new View({
center: fromLonLat([-100, 38.5]),
zoom: 4,
}),
});

界面布局文件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>Styling feature with CanvasGradient or CanvasPattern</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>