Search code examples
canvashtml5-canvasopenlayers

Canvas fillstyle to make background blacker


Here is a codepen of a simple OpenLayers map with an example overlay. My goal is to have essentially a dark mode OSM layer. I am currently using Mr. Mike's answer but am not quite there to match MapBox's contrast. I would love for a canvas wizard to help me with the styling of my map canvas in order to increase contrast but retain the topography markers.

Edit: This only works for OpenLayers 3 and I am currently trying to get the same result in OpenLayers 6


Solution

  • I have gotten acceptably close by using the following function on the basemap (OSM) postcompose event :

    map.getLayers().getArray()[0].on('postcompose', function (evt) {
        evt.context.globalCompositeOperation = 'color';
        evt.context.fillStyle = 'rgba(0,0,0,' + 1.0 + ')';
        evt.context.fillRect(0, 0, evt.context.canvas.width, evt.context.canvas.height);
        evt.context.globalCompositeOperation = 'overlay';
        evt.context.fillStyle = 'rgb(' + [200,200,200].toString() + ')';
        evt.context.fillRect(0, 0, evt.context.canvas.width, evt.context.canvas.height);
        evt.context.globalCompositeOperation = 'source-over';
        document.querySelector('canvas').style.filter="invert(99%)";
    });
    

    Which results in a dark OSM basemap. I am still hoping a `canvas wizard would improve my answer in performance, conciseness and clarity, but here is an example of what the resulting map looks like with an example layer. enter image description here