'Openlayers 5 Darken the Map
I want to have a dark map just like in the photo in order to make the other features inside the other layers more visible. What is the best approach to achieving this?
map = new ol.Map({
layers: [
new ol.layer.Tile({
source: new ol.source.OSM({
wrapX: false
})
}),
trackLayer,
circleMarkerLayer,
missionLayer,
planeLayer,
vesselLayer
],
target: 'map',
controls: ol.control.defaults({
attributionOptions: {
collapsible: false
},
attribution: false
}),
loadTilesWhileAnimating: true,
view: view
});
Solution 1:[1]
You can apply global composite operations at the base layer's postrender event to apply grayscale and other effects (note that the latest version of Chrome has a problem with this).
<!doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/css/ol.css" type="text/css">
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=requestAnimationFrame,Element.prototype.classList,URL"></script>
<script src="https://cdn.rawgit.com/openlayers/openlayers.github.io/master/en/v5.3.0/build/ol.js"></script>
<style>
html, body {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
}
.map {
margin: 0;
padding: 0;
width: 100%;
height: 80%;
}
</style>
</head>
<body>
<div id="map" class="map"></div>
<table><tr>
<th>Gray</th><th>Intensity</th>
</tr><tr>
<td><input id="gray" type="range" min="0" max="100" step="1" value="50"></td>
<td><input id="intensity" type="range" min="0" max="255" step="1" value="128"></td>
</tr></table>
<script type="text/javascript">
var map = new ol.Map({
layers : [
new ol.layer.Tile({source : new ol.source.OSM()}),
],
target : 'map',
logo: false,
controls: ol.control.defaults({ attributionOptions: { collapsible: false } }),
view : new ol.View({
center: ol.proj.fromLonLat([12.5, 55.7]),
zoom: 7
})
});
var intensityInput = document.getElementById('intensity');
var background = 255 - intensityInput.value;
intensityInput.onchange = function() {
background = 255 - intensityInput.value;
map.render();
};
var grayInput = document.getElementById('gray');
grayInput.onchange = function() {
map.render();
};
map.getLayers().getArray()[0].on('postcompose', function (evt) {
evt.context.globalCompositeOperation = 'color';
evt.context.fillStyle = 'rgba(255,255,255,' + grayInput.value/100 + ')';
evt.context.fillRect(0, 0, evt.context.canvas.width, evt.context.canvas.height);
evt.context.globalCompositeOperation = 'overlay';
evt.context.fillStyle = 'rgb(' + [background,background,background].toString() + ')';
evt.context.fillRect(0, 0, evt.context.canvas.width, evt.context.canvas.height);
evt.context.globalCompositeOperation = 'source-over';
});
</script>
</body>
</html>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |

