From 93b273218f022ca13a0faf2cd636685ac1724b1d Mon Sep 17 00:00:00 2001 From: Guilhem Moulin Date: Sat, 13 Jan 2024 20:02:23 +0100 Subject: Add ability to download PNG exports. Inspired from https://openlayers.org/en/latest/examples/export-map.html . --- main.js | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) (limited to 'main.js') diff --git a/main.js b/main.js index d542434..541ec27 100644 --- a/main.js +++ b/main.js @@ -236,6 +236,56 @@ const menu = document.getElementById('map-menu'); }) })(); +/* export/download button */ +(function() { + const div = document.createElement('div'); + div.classList.add('ol-unselectable', 'ol-control'); + div.id = 'export-to-image'; + + const btn = document.createElement('button'); + div.appendChild(btn); + btn.classList.add('btn', 'btn-light'); + btn.type = 'button'; + btn.title = 'Ladda ner som en PNG-fil'; + + const i = document.createElement('i'); + btn.appendChild(i); + i.classList.add('bi', 'bi-download'); + menu.appendChild(div); + + btn.onclick = function(event) { + map.once('rendercomplete', function() { + const canvas0 = document.createElement('canvas'); + const size = map.getSize(); + canvas0.width = size[0]; + canvas0.height = size[1]; + + const context = canvas0.getContext('2d'); + map.getViewport().querySelectorAll('.ol-layer canvas, canvas.ol-layer').forEach(function(canvas) { + if (canvas.width > 0) { + const opacity = canvas.parentNode.style.opacity || canvas.style.opacity; + context.globalAlpha = opacity === '' ? 1 : Number(opacity); + context.drawImage(canvas, 0, 0); + } + }); + + context.globalAlpha = 1; + context.setTransform(1, 0, 0, 1, 0, 0); + + canvas0.toBlob(function(blob) { + const a = document.createElement('a'); + a.download = 'karta.png'; + a.rel = 'noopener'; + a.href = URL.createObjectURL(blob); + setTimeout(function() { URL.revokeObjectURL(a.href) }, 4E4); // 40s + setTimeout(function() { a.click() }, 0); + }); + }); + + map.renderSync(); + }; +})(); + /* info button */ (function() { const div = document.createElement('div'); -- cgit v1.2.3