Home  >  Q&A  >  body text

Apply the openlayers filter and leave it unchanged when I save the map as an image

I made an openlayers map with various polylines on it. I'm using the default openstreetmap layer, but want to darken it to make my polylines stand out. I found that I can do this as follows:

map.getLayers().getArray()[0].on('postcompose', function (evt) {
   evt.context.canvas.style.filter="invert(99%)";
});

However, I also want my users to be able to download this map in PNG format. To do this, I use the following code, triggered by clicking a button:

map.once('postcompose', function(event) {
   var canvas = event.context.canvas;
   if (navigator.msSaveBlob) {
      navigator.msSaveBlob(canvas.msToBlob(), 'mymap.png');
   } else {
      canvas.toBlob(function(blob) {
         saveAs(blob, 'mymap.png')
      });
   }
});
map.renderSync();

Unfortunately this does not preserve the modifications I made to resize the canvas.

Can anyone help me? Thank you for reading.

P粉951914381P粉951914381427 days ago585

reply all(1)I'll reply

  • P粉252423906

    P粉2524239062023-09-11 00:07:01

    Setting a style filter on an element will not affect the output of toBlob() or toDataURL(). If you want to change the canvas context rather than how the browser renders the canvas, you will need a globalCompositeOperation (judging from the code you are using, I assume you are using OpenLayers 5):

    map.getLayers().getArray()[0].on('postcompose', function (evt) {
      evt.context.globalCompositeOperation = 'difference';
      evt.context.fillStyle = 'white';
      evt.context.fillRect(0, 0, evt.context.canvas.width, evt.context.canvas.height);
      evt.context.globalCompositeOperation = 'source-over';
    });

    reply
    0
  • Cancelreply