aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorGuilhem Moulin <guilhem@fripost.org>2024-01-13 20:02:23 +0100
committerGuilhem Moulin <guilhem@fripost.org>2024-01-14 04:14:12 +0100
commit93b273218f022ca13a0faf2cd636685ac1724b1d (patch)
tree03f445b3aed2dac6eebe3cc3f8e28d555ee1e067
parente6acb7eef6c243c6dbabd90bc235480f3b44324d (diff)
Add ability to download PNG exports.
Inspired from https://openlayers.org/en/latest/examples/export-map.html .
-rw-r--r--main.js50
-rw-r--r--style.css1
2 files changed, 51 insertions, 0 deletions
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');
diff --git a/style.css b/style.css
index 106315e..cbb4c02 100644
--- a/style.css
+++ b/style.css
@@ -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;