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

ruyhziif  于 2023-01-29  发布在  Java
关注(0)|答案(3)|浏览(883)

我喜欢使用openlayersMap与黑暗和光明的风格。那么我怎么能改变Map颜色或Map风格?我的朋友(亲爱的morteza)发现了一个简单的方法,我回答了这篇文章。我的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>
vdgimpew

vdgimpew1#

openlayes显示<canvas>中的Map。和<canvas>将被添加到<div>容器与openlayers库。所以添加以下代码添加Map和改变它的颜色:

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%)";
  });

您也可以测试其他筛选器

ubof19bj

ubof19bj2#

ol-ext库允许你在openlayers图层上设置滤镜,它使用画布合成操作来实现效果。
请在线查看代码示例:https://viglino.github.io/ol-ext/examples/filter/map.filter.colorize.html

fslejnso

fslejnso3#

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';
  }
});

在渲染平铺层之前设置画布过滤器,并在渲染后重置为无,这样做,以下层将不会受到任何影响,效果如下:
第一节第一节第一节第一节第一次

相关问题