我已经将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');