将导出到PNG功能添加到OpenLayers

我已经将html2canvas与OpenLayers 6.1.1版结合在一起,希望能提供一个更好的导出到PNG的示例。

我尝试将OpenLayers站点上显示的示例合并到我的应用程序中,但是并不能在所有浏览器(尤其是Safari)上正常工作。

<script type='text/javascript' src='javascript/html2canvas.min.js'></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=fetch,requestAnimationFrame,Element.prototype.classList,URL,Promise"></script>

使用这些javascript库和当前版本的OpenLayers(6.1.1),我添加了一个显示在地图上的按钮,该按钮具有以下功能:

var button_p = document.createElement('button');
button_p.innerHTML = 'PNG';
button_p.title = 'Export map as png.';

var pngfunction = function() {
  map.once('rendercomplete',function(event) {
    html2canvas(document.getElementById('map')).then(function(canvas) {
      var ctx = canvas.getcontext("2d");
      var now = new Date();
      var monthy = now.getMonth() + 1; // remember months are stored in array numbered 0-11
      ctx.fillStyle = "#0000FF";
      ctx.font = "12px Arial";
      ctx.fillText(monthy + "-" + now.getDate() + "-" + now.getFullYear() + " " + now.getHours() + ":" + (now.getMinutes() < 10 ? '0' : '') + now.getMinutes() + ":" + (now.getSeconds() < 10 ? '0' : '') + now.getSeconds(),10,20);

      if (navigator.msSaveBlob) {
    navigator.msSaveBlob(canvas.msToBlob(),'map.png');
      } else {
    canvas.toBlob(function(blob) {
      saveAs(blob,'map.png');
        });
      }
    });
  });
  map.renderSync();
};
button_p.addEventListener('click',pngfunction,false);

由于此按钮是'ol-control'类的一部分,并且我不希望这些控件成为结果PNG的一部分,因此我将这些项目四舍五入,并应用以下代码从PNG中删除这些控件:

var removals = document.getElementsByClassname('ol-control');
for(var i=0; i < removals.length; i++) { removals[i].setattribute('data-html2canvas-ignore','true'); }

但是,由于我想看向北的箭头,因此删除了我使用以下方法添加到该控件中的该属性:

document.getElementsByClassname('ol-rotate')[0].removeAttribute('data-html2canvas-ignore');
a839672614 回答:将导出到PNG功能添加到OpenLayers

看看ol-et Print control以获得ol映射的图像。

,

我用它来将ol-map导出为png:

map.once('rendercomplete',function() {
    var target = map.getViewport();
    // options for html2canvas to filter out all the 'ol-control' elements
    var configOptions = {
        ignoreElements: function(target) {
            return (target.className.indexOf('ol-control') !== -1); },logging: false
    };
    html2canvas(target,configOptions)
        .then(function(canvas) {
            canvas.toBlob(function(blob) {
            saveAs(blob,'map.png');
            });
    });
});

本文链接:https://www.f2er.com/3155995.html

大家都在问