Search code examples
javascriptpngopenlayers

OpenLayers - save map as png image with custom name


I would like to save my map as the .png image. I've managed to do so with the code below. Unfortunately, it looks like something is missing, as I cannot save it under the custom name.

document.getElementById('export-png').addEventListener('click', function () {
  map.once('rendercomplete', function () {
  var mapCanvas = document.createElement('canvas');
  var size = map.getSize();
  mapCanvas.width = size[0];
  mapCanvas.height = size[1];
  var mapContext = mapCanvas.getContext('2d');
  Array.prototype.forEach.call(
  document.querySelectorAll('.ol-layer canvas'),
  function (canvas) {
    if (canvas.width > 0) {
      var opacity = canvas.parentNode.style.opacity;
      mapContext.globalAlpha = opacity === '' ? 1 : Number(opacity);
      var transform = canvas.style.transform;
      // Get the transform parameters from the style's transform matrix
      var matrix = transform
        .match(/^matrix\(([^\(]*)\)$/)[1]
        .split(',')
        .map(Number);
      // Apply the transform to the export map context
      CanvasRenderingContext2D.prototype.setTransform.apply(
        mapContext,
        matrix
      );
      mapContext.drawImage(canvas, 0, 0);
    }
  }
 );
 if (navigator.msSaveBlob) {
   // link download attribuute does not work on MS browsers
   var imgName = prompt("Please provide the name", "survey_map");
   navigator.msSaveBlob(mapCanvas.msToBlob(), imgName + '.png');
 } else {
   var link = document.getElementById('image-download');
   link.href = mapCanvas.toDataURL();
   link.click();
 }
});
 map.renderSync();
 });

I used the prompt property, but it looks like it doesn't work here.

enter image description here

Is it possible to set the custom name for this png image?


Solution

  • Your code would only work for Internet Explorer and legacy Edge. For other browsers you need to set the download attribute of the link. You should also check if the cancel button was clicked (otherwise you would download null.png)

     var imgName = prompt("Please provide the name", "survey_map");
     if (imgName) {
       if (navigator.msSaveBlob) {
         // link download attribuute does not work on MS browsers
         navigator.msSaveBlob(mapCanvas.msToBlob(), imgName + '.png');
       } else {
         var link = document.getElementById('image-download');
         link.download = imgName + '.png';
         link.href = mapCanvas.toDataURL();
         link.click();
       }
     }