diff options
author | Guilhem Moulin <guilhem@fripost.org> | 2024-01-13 20:02:23 +0100 |
---|---|---|
committer | Guilhem Moulin <guilhem@fripost.org> | 2024-01-14 04:14:12 +0100 |
commit | 93b273218f022ca13a0faf2cd636685ac1724b1d (patch) | |
tree | 03f445b3aed2dac6eebe3cc3f8e28d555ee1e067 | |
parent | e6acb7eef6c243c6dbabd90bc235480f3b44324d (diff) |
Add ability to download PNG exports.
Inspired from https://openlayers.org/en/latest/examples/export-map.html .
-rw-r--r-- | main.js | 50 | ||||
-rw-r--r-- | style.css | 1 |
2 files changed, 51 insertions, 0 deletions
@@ -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'); @@ -196,6 +196,7 @@ html, body { display: none; } #layer-selection-button, + #export-to-image, #map-menu #layer-selection-panel, #map-menu .ol-full-screen { display: none; |