简体   繁体   English

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

[英]OpenLayers - save map as png image with custom name

I would like to save my map as the.png image.我想将我的 map 保存为 .png 图像。 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.我使用了 prompt 属性,但它看起来在这里不起作用。

在此处输入图像描述

Is it possible to set the custom name for this png image?是否可以为此 png 图像设置自定义名称?

Your code would only work for Internet Explorer and legacy Edge.您的代码仅适用于 Internet Explorer 和旧版 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)您还应该检查是否单击了取消按钮(否则您将下载 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();
   }
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM