原文链接及内容

运行界面

可以调用layer.setopacity()方法来调整图层的透明度。

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
import Map from 'ol/Map.js';
import OSM from 'ol/source/OSM.js';
import TileLayer from 'ol/layer/WebGLTile.js';
import View from 'ol/View.js';
import XYZ from 'ol/source/XYZ.js';

const key = 'Get your own API key at https://www.maptiler.com/cloud/';

const imagery = new TileLayer({
className: 'ol-layer-imagery',
source: new XYZ({
attributions:
'<a href="https://www.maptiler.com/copyright/" target="_blank">&copy; MapTiler</a> ',
url: 'https://api.maptiler.com/tiles/satellite/{z}/{x}/{y}.jpg?key=' + key,
maxZoom: 20,
crossOrigin: '',
}),
});

const osm = new TileLayer({
source: new OSM(),
});

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

const opacityInput = document.getElementById('opacity-input');
const opacityOutput = document.getElementById('opacity-output');
function update() {
const opacity = parseFloat(opacityInput.value);
osm.setOpacity(opacity);
opacityOutput.innerText = opacity.toFixed(2);
}
opacityInput.addEventListener('input', update);
update();

界面布局文件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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Layer Opacity</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>
<label>
Layer opacity
<input id="opacity-input" type="range" min="0" max="1" step="0.01" value="1" />
<span id="opacity-output"></span>
</label>
<!-- 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>