更改 openlayers 贴图颜色(深色和浅色样式)

问题描述 投票:0回答:4

我喜欢使用深色和浅色风格的 openlayers 贴图。那么如何更改地图颜色或地图样式呢? 我的朋友(亲爱的莫特扎)找到了我在这篇文章中回答的简单方法。 我的 html 文件是:

<!doctype html>
<html lang="en">
  <head>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/css/ol.css" type="text/css">
    <style>
      .map {
        height: 400px;
        width: 50%;
      }
    </style>
    <script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io@master/en/v6.1.1/build/ol.js"></script>
    <title>OpenLayers example</title>
  </head>
  <body>
    <h2>My Map</h2>
    <div id="map" class="map"></div>
    <script type="text/javascript">
      var map = new ol.Map({
        target: 'map',
        layers: [
          new ol.layer.Tile({
            source: new ol.source.OSM()
          })
        ],
        view: new ol.View({
          center: ol.proj.fromLonLat([37.41, 8.82]),
          zoom: 4
        })
      });

	  // function applies greyscale to every pixel in canvas
    </script>
  </body>
</html>

javascript dictionary openlayers
4个回答
5
投票

openlayes 在

<canvas>
中显示地图。和
<canvas>
将添加到带有 openlayers 库的
<div>
容器中。因此,添加以下代码来添加地图并更改其颜色:

var map = new ol.Map({
    target: 'map',//div with map id
    layers: [
          new ol.layer.Tile({
              source: new ol.source.OSM()
            })
        ],
    view: new ol.View({
        center: ol.proj.fromLonLat([61.2135, 28.2331]),
        zoom: 13 
      })
  });
//change map color
map.on('postcompose',function(e){
    document.querySelector('canvas').style.filter="invert(90%)";
  });

您还可以测试其他过滤器


5
投票
const tile = new TileLayer({
  source: new OSM()
});
tile.on('prerender', (evt) => {
  // return
  if (evt.context) {
    const context = evt.context as CanvasRenderingContext2D;
    context.filter = 'grayscale(80%) invert(100%) ';
    context.globalCompositeOperation = 'source-over';
  }
});

tile.on('postrender', (evt) => {
  if (evt.context) {
    const context = evt.context as CanvasRenderingContext2D;
    context.filter = 'none';
  }
});

在瓦片图层渲染前设置canvas滤镜,渲染后重置回无,这样后面的图层就不会受到任何影响,效果如下:


2
投票

ol-ext 库允许您在 openlayers 图层上设置过滤器。它使用canvas合成操作来实现效果。

在线查看代码示例:https://viglino.github.io/ol-ext/examples/filter/map.filter.colorize.html


0
投票

Guichi答案效果很好,但我推荐其他过滤器invert(100%) hue-rotate(180deg)

以保持绿色和蓝色:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.