OpenLayers - 将地图保存为具有自定义名称的 png 图像

OpenLayers - save map as png image with custom name

我想将我的地图保存为 .png 图像。 我已经设法用下面的代码做到了。不幸的是,它似乎缺少一些东西,因为我无法将其保存在自定义名称下。

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

我使用了提示符属性,但在这里似乎不起作用。

是否可以为此 png 图片设置自定义名称?

您的代码仅适用于 Internet Explorer 和旧版 Edge。对于其他浏览器,您需要设置 link 的下载属性。您还应该检查是否单击了取消按钮(否则您将下载 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();
   }
 }