fix: move scaleBar to the corner of svg export

This commit is contained in:
Azgaar 2023-11-19 20:10:42 +04:00
parent 20b09e8634
commit 433152db06
9 changed files with 153 additions and 156 deletions

View file

@ -1632,7 +1632,7 @@ div.states > .riverType {
padding: 0.3em 0; padding: 0.3em 0;
} }
#saveTilesScreen div.label { #exportToPngTilesScreen div.label {
display: inline-block; display: inline-block;
width: 5em; width: 5em;
} }

View file

@ -5776,18 +5776,24 @@
<div style="margin-bottom: 0.3em; font-weight: bold">Download image</div> <div style="margin-bottom: 0.3em; font-weight: bold">Download image</div>
<div> <div>
<button <button
onclick="saveSVG()" onclick="exportToSvg()"
data-tip="Download the map as vector image (open directly in browser or Inkscape)" data-tip="Download the map as vector image (open directly in browser or Inkscape)"
> >
.svg .svg
</button> </button>
<button onclick="savePNG()" data-tip="Download visible part of the map as .png (lossless compressed)"> <button onclick="exportToPng()" data-tip="Download visible part of the map as .png (lossless compressed)">
.png .png
</button> </button>
<button onclick="saveJPEG()" data-tip="Download visible part of the map as .jpeg (lossy compressed) image"> <button
onclick="exportToJpeg()"
data-tip="Download visible part of the map as .jpeg (lossy compressed) image"
>
.jpeg .jpeg
</button> </button>
<button onclick="openSaveTiles()" data-tip="Split map into smaller png tiles and download as zip archive"> <button
onclick="openExportToPngTiles()"
data-tip="Split map into smaller png tiles and download as zip archive"
>
tiles tiles
</button> </button>
<span data-tip="Check to not allow system to automatically hide labels"> <span data-tip="Check to not allow system to automatically hide labels">
@ -5921,7 +5927,7 @@
</div> </div>
</div> </div>
<div id="saveTilesScreen" style="display: none" class="dialog"> <div id="exportToPngTilesScreen" style="display: none" class="dialog">
<p>Map will be split into tiles and downloaded as a single zip file. Avoid saving to big images</p> <p>Map will be split into tiles and downloaded as a single zip file. Avoid saving to big images</p>
<div data-tip="Number of columns" style="margin-bottom: 0.3em"> <div data-tip="Number of columns" style="margin-bottom: 0.3em">
<div class="label">Columns:</div> <div class="label">Columns:</div>
@ -7936,12 +7942,12 @@
<script src="libs/alea.min.js"></script> <script src="libs/alea.min.js"></script>
<script src="modules/fonts.js?v=1.89.18"></script> <script src="modules/fonts.js?v=1.89.18"></script>
<script src="modules/ui/layers.js?v=1.94.00"></script> <script src="modules/ui/layers.js?v=1.94.00"></script>
<script src="modules/ui/measurers.js?v=1.87.02"></script> <script src="modules/ui/measurers.js?v=1.94.02"></script>
<script src="modules/ui/stylePresets.js?v=1.94.00"></script> <script src="modules/ui/stylePresets.js?v=1.94.00"></script>
<script src="modules/ui/general.js?v=1.94.01"></script> <script src="modules/ui/general.js?v=1.94.01"></script>
<script src="modules/ui/options.js?v=1.94.01"></script> <script src="modules/ui/options.js?v=1.94.02"></script>
<script src="main.js?v=1.94.01"></script> <script src="main.js?v=1.94.02"></script>
<script defer src="modules/relief-icons.js"></script> <script defer src="modules/relief-icons.js"></script>
<script defer src="modules/ui/style.js?v=1.94.00"></script> <script defer src="modules/ui/style.js?v=1.94.00"></script>
@ -7963,7 +7969,7 @@
<script defer src="modules/ui/rivers-creator.js?v=1.89.13"></script> <script defer src="modules/ui/rivers-creator.js?v=1.89.13"></script>
<script defer src="modules/ui/relief-editor.js"></script> <script defer src="modules/ui/relief-editor.js"></script>
<script defer src="modules/ui/burg-editor.js"></script> <script defer src="modules/ui/burg-editor.js"></script>
<script defer src="modules/ui/units-editor.js"></script> <script defer src="modules/ui/units-editor.js?v=1.94.02"></script>
<script defer src="modules/ui/notes-editor.js?v=1.93.09"></script> <script defer src="modules/ui/notes-editor.js?v=1.93.09"></script>
<script defer src="modules/ui/diplomacy-editor.js?v=1.88.04"></script> <script defer src="modules/ui/diplomacy-editor.js?v=1.88.04"></script>
<script defer src="modules/ui/zones-editor.js"></script> <script defer src="modules/ui/zones-editor.js"></script>
@ -7977,7 +7983,7 @@
<script defer src="modules/ui/emblems-editor.js?v=1.91.00"></script> <script defer src="modules/ui/emblems-editor.js?v=1.91.00"></script>
<script defer src="modules/ui/markers-editor.js"></script> <script defer src="modules/ui/markers-editor.js"></script>
<script defer src="modules/ui/3d.js?v=1.93.11"></script> <script defer src="modules/ui/3d.js?v=1.93.11"></script>
<script defer src="modules/ui/submap.js?v=1.92.00"></script> <script defer src="modules/ui/submap.js?v=1.94.02"></script>
<script defer src="modules/ui/hotkeys.js?v=1.93.00"></script> <script defer src="modules/ui/hotkeys.js?v=1.93.00"></script>
<script defer src="modules/coa-renderer.js?v=1.94.00"></script> <script defer src="modules/coa-renderer.js?v=1.94.00"></script>
<script defer src="libs/rgbquant.min.js"></script> <script defer src="libs/rgbquant.min.js"></script>
@ -7985,7 +7991,7 @@
<script defer src="modules/io/save.js?v=1.93.02"></script> <script defer src="modules/io/save.js?v=1.93.02"></script>
<script defer src="modules/io/load.js?v=1.94.01"></script> <script defer src="modules/io/load.js?v=1.94.01"></script>
<script defer src="modules/io/cloud.js"></script> <script defer src="modules/io/cloud.js"></script>
<script defer src="modules/io/export.js?v=1.94.00"></script> <script defer src="modules/io/export.js?v=1.94.02"></script>
<script defer src="modules/io/formats.js"></script> <script defer src="modules/io/formats.js"></script>
<!-- Web Components --> <!-- Web Components -->

View file

@ -429,7 +429,8 @@ function handleZoom(isScaleChanged, isPositionChanged) {
if (isScaleChanged) { if (isScaleChanged) {
invokeActiveZooming(); invokeActiveZooming();
drawScaleBar(scale); drawScaleBar(scaleBar, scale);
fitScaleBar(scaleBar, svgWidth, svgHeight);
} }
// zoom image converter overlay // zoom image converter overlay
@ -655,7 +656,7 @@ async function generate(options) {
Markers.generate(); Markers.generate();
addZones(); addZones();
drawScaleBar(scale); drawScaleBar(scaleBar, scale);
Names.getMapName(); Names.getMapName();
WARN && console.warn(`TOTAL: ${rn((performance.now() - timeStart) / 1000, 2)}s`); WARN && console.warn(`TOTAL: ${rn((performance.now() - timeStart) / 1000, 2)}s`);

View file

@ -1,27 +1,21 @@
"use strict"; "use strict";
// Functions to export map to image or data files // Functions to export map to image or data files
// download map as SVG async function exportToSvg() {
async function saveSVG() { TIME && console.time("exportToSvg");
TIME && console.time("saveSVG");
const url = await getMapURL("svg", {fullMap: true}); const url = await getMapURL("svg", {fullMap: true});
const link = document.createElement("a"); const link = document.createElement("a");
link.download = getFileName() + ".svg"; link.download = getFileName() + ".svg";
link.href = url; link.href = url;
link.click(); link.click();
tip( const message = `${link.download} is saved. Open 'Downloads' screen (ctrl + J) to check`;
`${link.download} is saved. Open "Downloads" screen (ctrl + J) to check. You can set image scale in options`, tip(message, true, "success", 5000);
true, TIME && console.timeEnd("exportToSvg");
"success",
5000
);
TIME && console.timeEnd("saveSVG");
} }
// download map as PNG async function exportToPng() {
async function savePNG() { TIME && console.time("exportToPng");
TIME && console.time("savePNG");
const url = await getMapURL("png"); const url = await getMapURL("png");
const link = document.createElement("a"); const link = document.createElement("a");
@ -41,22 +35,18 @@ async function savePNG() {
window.setTimeout(function () { window.setTimeout(function () {
canvas.remove(); canvas.remove();
window.URL.revokeObjectURL(link.href); window.URL.revokeObjectURL(link.href);
tip(
`${link.download} is saved. Open "Downloads" screen (crtl + J) to check. You can set image scale in options`, const message = `${link.download} is saved. Open 'Downloads' screen (ctrl + J) to check. You can set image scale in options`;
true, tip(message, true, "success", 5000);
"success",
5000
);
}, 1000); }, 1000);
}); });
}; };
TIME && console.timeEnd("savePNG"); TIME && console.timeEnd("exportToPng");
} }
// download map as JPEG async function exportToJpeg() {
async function saveJPEG() { TIME && console.time("exportToJpeg");
TIME && console.time("saveJPEG");
const url = await getMapURL("png"); const url = await getMapURL("png");
const canvas = document.createElement("canvas"); const canvas = document.createElement("canvas");
@ -77,11 +67,10 @@ async function saveJPEG() {
window.setTimeout(() => window.URL.revokeObjectURL(URL), 5000); window.setTimeout(() => window.URL.revokeObjectURL(URL), 5000);
}; };
TIME && console.timeEnd("saveJPEG"); TIME && console.timeEnd("exportToJpeg");
} }
// download map as png tiles async function exportToPngTiles() {
async function saveTiles() {
return new Promise(async (resolve, reject) => { return new Promise(async (resolve, reject) => {
// download schema // download schema
const urlSchema = await getMapURL("tiles", {debug: true, fullMap: true}); const urlSchema = await getMapURL("tiles", {debug: true, fullMap: true});
@ -160,8 +149,6 @@ async function getMapURL(type, options = {}) {
fullMap = false fullMap = false
} = options; } = options;
if (fullMap) drawScaleBar(1);
const cloneEl = document.getElementById("map").cloneNode(true); // clone svg const cloneEl = document.getElementById("map").cloneNode(true); // clone svg
cloneEl.id = "fantasyMap"; cloneEl.id = "fantasyMap";
document.body.appendChild(cloneEl); document.body.appendChild(cloneEl);
@ -183,13 +170,14 @@ async function getMapURL(type, options = {}) {
clone.select("#oceanBase").attr("opacity", 0); clone.select("#oceanBase").attr("opacity", 0);
clone.select("#oceanPattern").attr("opacity", 0); clone.select("#oceanPattern").attr("opacity", 0);
} }
if (noScaleBar) clone.select("#scaleBar")?.remove();
if (noIce) clone.select("#ice")?.remove(); if (noIce) clone.select("#ice")?.remove();
if (noScaleBar) clone.select("#scaleBar")?.remove();
if (fullMap) { if (fullMap) {
// reset transform to show the whole map // reset transform to show the whole map
clone.attr("width", graphWidth).attr("height", graphHeight); clone.attr("width", graphWidth).attr("height", graphHeight);
clone.select("#viewbox").attr("transform", null); clone.select("#viewbox").attr("transform", null);
drawScaleBar(scale); drawScaleBar(clone.select("#scaleBar"), 1);
fitScaleBar(clone.select("#scaleBar"), graphWidth, graphHeight);
} }
if (type === "svg") removeUnusedElements(clone); if (type === "svg") removeUnusedElements(clone);

View file

@ -42,7 +42,8 @@ window.Submap = (function () {
applyGraphSize(); applyGraphSize();
grid = generateGrid(); grid = generateGrid();
drawScaleBar(scale); drawScaleBar(scaleBar, scale);
fitScaleBar(scaleBar, svgWidth, svgHeight);
const resampler = (points, qtree, f) => { const resampler = (points, qtree, f) => {
for (const [i, [x, y]] of points.entries()) { for (const [i, [x, y]] of points.entries()) {

View file

@ -534,7 +534,7 @@ class Planimeter extends Measurer {
} }
// Scale bar // Scale bar
function drawScaleBar(scaleLevel) { function drawScaleBar(scaleBar, scaleLevel) {
if (scaleBar.style("display") === "none") return; // no need to re-draw hidden element if (scaleBar.style("display") === "none") return; // no need to re-draw hidden element
scaleBar.selectAll("*").remove(); // fully redraw every time scaleBar.selectAll("*").remove(); // fully redraw every time
@ -589,7 +589,7 @@ function drawScaleBar(scaleLevel) {
.append("text") .append("text")
.attr("x", d => rn((d * length) / 5, 2)) .attr("x", d => rn((d * length) / 5, 2))
.attr("y", 0) .attr("y", 0)
.attr("dy", "-.5em") .attr("dy", "-.6em")
.attr("font-size", fontSize) .attr("font-size", fontSize)
.text(d => rn((((d * length) / 5) * distanceScale) / scaleLevel) + (d < 5 ? "" : " " + unit)); .text(d => rn((((d * length) / 5) * distanceScale) / scaleLevel) + (d < 5 ? "" : " " + unit));
@ -616,19 +616,17 @@ function drawScaleBar(scaleLevel) {
.attr("filter", "url(#blur5)") .attr("filter", "url(#blur5)")
.attr("fill", barBackColor.value) .attr("fill", barBackColor.value)
.attr("opacity", +barBackOpacity.value); .attr("opacity", +barBackOpacity.value);
fitScaleBar();
} }
// fit ScaleBar to canvas size // fit ScaleBar to screen size
function fitScaleBar() { function fitScaleBar(scaleBar, fullWidth, fullHeight) {
if (!scaleBar.select("rect").size() || scaleBar.style("display") === "none") return; if (!scaleBar.select("rect").size() || scaleBar.style("display") === "none") return;
const px = isNaN(+barPosX.value) ? 0.99 : barPosX.value / 100; const px = isNaN(+barPosX.value) ? 0.99 : barPosX.value / 100;
const py = isNaN(+barPosY.value) ? 0.99 : barPosY.value / 100; const py = isNaN(+barPosY.value) ? 0.99 : barPosY.value / 100;
const bbox = scaleBar.select("rect").node().getBBox(); const bbox = scaleBar.select("rect").node().getBBox();
const x = rn(svgWidth * px - bbox.width + 10); const x = rn(fullWidth * px - bbox.width + 10);
const y = rn(svgHeight * py - bbox.height + 20); const y = rn(fullHeight * py - bbox.height + 20);
scaleBar.attr("transform", `translate(${x},${y})`); scaleBar.attr("transform", `translate(${x},${y})`);
} }

View file

@ -20,7 +20,7 @@ function showOptions(event) {
} }
regenerate.style.display = "none"; regenerate.style.display = "none";
document.getElementById("options").style.display = "block"; byId("options").style.display = "block";
optionsTrigger.style.display = "none"; optionsTrigger.style.display = "none";
if (event) event.stopPropagation(); if (event) event.stopPropagation();
@ -28,21 +28,21 @@ function showOptions(event) {
// Hide options pane on trigger click // Hide options pane on trigger click
function hideOptions(event) { function hideOptions(event) {
document.getElementById("options").style.display = "none"; byId("options").style.display = "none";
optionsTrigger.style.display = "block"; optionsTrigger.style.display = "block";
if (event) event.stopPropagation(); if (event) event.stopPropagation();
} }
// To toggle options on hotkey press // To toggle options on hotkey press
function toggleOptions(event) { function toggleOptions(event) {
if (document.getElementById("options").style.display === "none") showOptions(event); if (byId("options").style.display === "none") showOptions(event);
else hideOptions(event); else hideOptions(event);
} }
// Toggle "New Map!" pane on hover // Toggle "New Map!" pane on hover
optionsTrigger.addEventListener("mouseenter", function () { optionsTrigger.addEventListener("mouseenter", function () {
if (optionsTrigger.classList.contains("glow")) return; if (optionsTrigger.classList.contains("glow")) return;
if (document.getElementById("options").style.display === "none") regenerate.style.display = "block"; if (byId("options").style.display === "none") regenerate.style.display = "block";
}); });
collapsible.addEventListener("mouseleave", function () { collapsible.addEventListener("mouseleave", function () {
@ -56,11 +56,11 @@ document
.addEventListener("click", function (event) { .addEventListener("click", function (event) {
if (event.target.tagName !== "BUTTON") return; if (event.target.tagName !== "BUTTON") return;
const id = event.target.id; const id = event.target.id;
const active = document.getElementById("options").querySelector(".tab > button.active"); const active = byId("options").querySelector(".tab > button.active");
if (active && id === active.id) return; // already active tab is clicked if (active && id === active.id) return; // already active tab is clicked
if (active) active.classList.remove("active"); if (active) active.classList.remove("active");
document.getElementById(id).classList.add("active"); byId(id).classList.add("active");
document document
.getElementById("options") .getElementById("options")
.querySelectorAll(".tabcontent") .querySelectorAll(".tabcontent")
@ -91,10 +91,10 @@ async function showSupporters() {
} }
// on any option or dialog change // on any option or dialog change
document.getElementById("options").addEventListener("change", storeValueIfRequired); byId("options").addEventListener("change", storeValueIfRequired);
document.getElementById("dialogs").addEventListener("change", storeValueIfRequired); byId("dialogs").addEventListener("change", storeValueIfRequired);
document.getElementById("options").addEventListener("input", updateOutputToFollowInput); byId("options").addEventListener("input", updateOutputToFollowInput);
document.getElementById("dialogs").addEventListener("input", updateOutputToFollowInput); byId("dialogs").addEventListener("input", updateOutputToFollowInput);
function storeValueIfRequired(ev) { function storeValueIfRequired(ev) {
if (ev.target.dataset.stored) lock(ev.target.dataset.stored); if (ev.target.dataset.stored) lock(ev.target.dataset.stored);
@ -109,16 +109,16 @@ function updateOutputToFollowInput(ev) {
// generic case // generic case
if (id.slice(-5) === "Input") { if (id.slice(-5) === "Input") {
const output = document.getElementById(id.slice(0, -5) + "Output"); const output = byId(id.slice(0, -5) + "Output");
if (output) output.value = value; if (output) output.value = value;
} else if (id.slice(-6) === "Output") { } else if (id.slice(-6) === "Output") {
const input = document.getElementById(id.slice(0, -6) + "Input"); const input = byId(id.slice(0, -6) + "Input");
if (input) input.value = value; if (input) input.value = value;
} }
} }
// Option listeners // Option listeners
const optionsContent = document.getElementById("optionsContent"); const optionsContent = byId("optionsContent");
optionsContent.addEventListener("input", function (event) { optionsContent.addEventListener("input", function (event) {
const id = event.target.id; const id = event.target.id;
const value = event.target.value; const value = event.target.value;
@ -216,7 +216,7 @@ function fitMapToScreen() {
zoom.translateExtent(zoomExtent).scaleExtent([zoomMin, zoomMax]).scaleTo(svg, zoomMin); zoom.translateExtent(zoomExtent).scaleExtent([zoomMin, zoomMax]).scaleTo(svg, zoomMin);
fitScaleBar(); fitScaleBar(scaleBar, svgWidth, svgHeight);
if (window.fitLegendBox) fitLegendBox(); if (window.fitLegendBox) fitLegendBox();
} }
@ -241,7 +241,7 @@ const voiceInterval = setInterval(function () {
if (voices.length) clearInterval(voiceInterval); if (voices.length) clearInterval(voiceInterval);
else return; else return;
const select = document.getElementById("speakerVoice"); const select = byId("speakerVoice");
voices.forEach((voice, i) => { voices.forEach((voice, i) => {
select.options.add(new Option(voice.name, i, false)); select.options.add(new Option(voice.name, i, false));
}); });
@ -255,7 +255,7 @@ function testSpeaker() {
const speaker = new SpeechSynthesisUtterance(text); const speaker = new SpeechSynthesisUtterance(text);
const voices = speechSynthesis.getVoices(); const voices = speechSynthesis.getVoices();
if (voices.length) { if (voices.length) {
const voiceId = +document.getElementById("speakerVoice").value; const voiceId = +byId("speakerVoice").value;
speaker.voice = voices[voiceId]; speaker.voice = voices[voiceId];
} }
speechSynthesis.speak(speaker); speechSynthesis.speak(speaker);
@ -348,7 +348,7 @@ function changeCultureSet() {
} }
function changeEmblemShape(emblemShape) { function changeEmblemShape(emblemShape) {
const image = document.getElementById("emblemShapeImage"); const image = byId("emblemShapeImage");
const shapePath = window.COArenderer && COArenderer.shieldPaths[emblemShape]; const shapePath = window.COArenderer && COArenderer.shieldPaths[emblemShape];
shapePath ? image.setAttribute("d", shapePath) : image.removeAttribute("d"); shapePath ? image.setAttribute("d", shapePath) : image.removeAttribute("d");
@ -357,7 +357,7 @@ function changeEmblemShape(emblemShape) {
pack.cultures.filter(c => !c.removed).forEach(c => (c.shield = Cultures.getRandomShield())); pack.cultures.filter(c => !c.removed).forEach(c => (c.shield = Cultures.getRandomShield()));
const rerenderCOA = (id, coa) => { const rerenderCOA = (id, coa) => {
const coaEl = document.getElementById(id); const coaEl = byId(id);
if (!coaEl) return; // not rendered if (!coaEl) return; // not rendered
coaEl.remove(); coaEl.remove();
COArenderer.trigger(id, coa); COArenderer.trigger(id, coa);
@ -403,7 +403,7 @@ function changeUiSize(value) {
uiSizeInput.value = uiSizeOutput.value = value; uiSizeInput.value = uiSizeOutput.value = value;
document.getElementsByTagName("body")[0].style.fontSize = rn(value * 10, 2) + "px"; document.getElementsByTagName("body")[0].style.fontSize = rn(value * 10, 2) + "px";
document.getElementById("options").style.width = value * 300 + "px"; byId("options").style.width = value * 300 + "px";
} }
function getUImaxSize() { function getUImaxSize() {
@ -463,7 +463,7 @@ function loadGoogleTranslate() {
const script = document.createElement("script"); const script = document.createElement("script");
script.src = "https://translate.google.com/translate_a/element.js?cb=initGoogleTranslate"; script.src = "https://translate.google.com/translate_a/element.js?cb=initGoogleTranslate";
script.onload = () => { script.onload = () => {
document.getElementById("loadGoogleTranslateButton")?.remove(); byId("loadGoogleTranslateButton")?.remove();
// replace mapLayers underline <u> with bare text to avoid translation issue // replace mapLayers underline <u> with bare text to avoid translation issue
document document
@ -702,7 +702,7 @@ function restoreDefaultOptions() {
} }
// Sticked menu Options listeners // Sticked menu Options listeners
document.getElementById("sticked").addEventListener("click", function (event) { byId("sticked").addEventListener("click", function (event) {
const id = event.target.id; const id = event.target.id;
if (id === "newMapButton") regeneratePrompt(); if (id === "newMapButton") regeneratePrompt();
else if (id === "saveButton") showSavePane(); else if (id === "saveButton") showSavePane();
@ -735,7 +735,7 @@ function regeneratePrompt(options) {
} }
function showSavePane() { function showSavePane() {
const sharableLinkContainer = document.getElementById("sharableLinkContainer"); const sharableLinkContainer = byId("sharableLinkContainer");
sharableLinkContainer.style.display = "none"; sharableLinkContainer.style.display = "none";
$("#saveMapData").dialog({ $("#saveMapData").dialog({
@ -752,13 +752,13 @@ function showSavePane() {
} }
function copyLinkToClickboard() { function copyLinkToClickboard() {
const shrableLink = document.getElementById("sharableLink"); const shrableLink = byId("sharableLink");
const link = shrableLink.getAttribute("href"); const link = shrableLink.getAttribute("href");
navigator.clipboard.writeText(link).then(() => tip("Link is copied to the clipboard", true, "success", 8000)); navigator.clipboard.writeText(link).then(() => tip("Link is copied to the clipboard", true, "success", 8000));
} }
function showExportPane() { function showExportPane() {
document.getElementById("showLabels").checked = !hideLabels.checked; byId("showLabels").checked = !hideLabels.checked;
$("#exportMapData").dialog({ $("#exportMapData").dialog({
title: "Export map data", title: "Export map data",
@ -793,10 +793,10 @@ async function showLoadPane() {
// already connected to Dropbox: list saved maps // already connected to Dropbox: list saved maps
if (Cloud.providers.dropbox.api) { if (Cloud.providers.dropbox.api) {
document.getElementById("dropboxConnectButton").style.display = "none"; byId("dropboxConnectButton").style.display = "none";
document.getElementById("loadFromDropboxSelect").style.display = "block"; byId("loadFromDropboxSelect").style.display = "block";
const loadFromDropboxButtons = document.getElementById("loadFromDropboxButtons"); const loadFromDropboxButtons = byId("loadFromDropboxButtons");
const fileSelect = document.getElementById("loadFromDropboxSelect"); const fileSelect = byId("loadFromDropboxSelect");
fileSelect.innerHTML = /* html */ `<option value="" disabled selected>Loading...</option>`; fileSelect.innerHTML = /* html */ `<option value="" disabled selected>Loading...</option>`;
const files = await Cloud.providers.dropbox.list(); const files = await Cloud.providers.dropbox.list();
@ -821,9 +821,9 @@ async function showLoadPane() {
} }
// not connected to Dropbox: show connect button // not connected to Dropbox: show connect button
document.getElementById("dropboxConnectButton").style.display = "inline-block"; byId("dropboxConnectButton").style.display = "inline-block";
document.getElementById("loadFromDropboxButtons").style.display = "none"; byId("loadFromDropboxButtons").style.display = "none";
document.getElementById("loadFromDropboxSelect").style.display = "none"; byId("loadFromDropboxSelect").style.display = "none";
} }
async function connectToDropbox() { async function connectToDropbox() {
@ -859,24 +859,24 @@ function loadURL() {
} }
// load map // load map
document.getElementById("mapToLoad").addEventListener("change", function () { byId("mapToLoad").addEventListener("change", function () {
const fileToLoad = this.files[0]; const fileToLoad = this.files[0];
this.value = ""; this.value = "";
closeDialogs(); closeDialogs();
uploadMap(fileToLoad); uploadMap(fileToLoad);
}); });
function openSaveTiles() { function openExportToPngTiles() {
closeDialogs(); closeDialogs();
updateTilesOptions(); updateTilesOptions();
const status = document.getElementById("tileStatus"); const status = byId("tileStatus");
status.innerHTML = ""; status.innerHTML = "";
let loading = null; let loading = null;
const inputs = document.getElementById("saveTilesScreen").querySelectorAll("input"); const inputs = byId("exportToPngTilesScreen").querySelectorAll("input");
inputs.forEach(input => input.addEventListener("input", updateTilesOptions)); inputs.forEach(input => input.addEventListener("input", updateTilesOptions));
$("#saveTilesScreen").dialog({ $("#exportToPngTilesScreen").dialog({
resizable: false, resizable: false,
title: "Download tiles", title: "Download tiles",
width: "23em", width: "23em",
@ -885,7 +885,7 @@ function openSaveTiles() {
status.innerHTML = "Preparing for download..."; status.innerHTML = "Preparing for download...";
setTimeout(() => (status.innerHTML = "Downloading. It may take some time."), 1000); setTimeout(() => (status.innerHTML = "Downloading. It may take some time."), 1000);
loading = setInterval(() => (status.innerHTML += "."), 1000); loading = setInterval(() => (status.innerHTML += "."), 1000);
saveTiles().then(() => { exportToPngTiles().then(() => {
clearInterval(loading); clearInterval(loading);
status.innerHTML = /* html */ `Done. Check file in "Downloads" (crtl + J)`; status.innerHTML = /* html */ `Done. Check file in "Downloads" (crtl + J)`;
setTimeout(() => (status.innerHTML = ""), 8000); setTimeout(() => (status.innerHTML = ""), 8000);
@ -910,10 +910,10 @@ function updateTilesOptions() {
if (prev?.tagName === "INPUT") prev.value = this.value; if (prev?.tagName === "INPUT") prev.value = this.value;
} }
const tileSize = document.getElementById("tileSize"); const tileSize = byId("tileSize");
const tilesX = +document.getElementById("tileColsOutput").value; const tilesX = +byId("tileColsOutput").value;
const tilesY = +document.getElementById("tileRowsOutput").value; const tilesY = +byId("tileRowsOutput").value;
const scale = +document.getElementById("tileScaleOutput").value; const scale = +byId("tileScaleOutput").value;
// calculate size // calculate size
const sizeX = graphWidth * scale * tilesX; const sizeX = graphWidth * scale * tilesX;
@ -962,9 +962,9 @@ function enterStandardView() {
heightmap3DView.classList.remove("pressed"); heightmap3DView.classList.remove("pressed");
viewStandard.classList.add("pressed"); viewStandard.classList.add("pressed");
if (!document.getElementById("canvas3d")) return; if (!byId("canvas3d")) return;
ThreeD.stop(); ThreeD.stop();
document.getElementById("canvas3d").remove(); byId("canvas3d").remove();
if (options3dUpdate.offsetParent) $("#options3d").dialog("close"); if (options3dUpdate.offsetParent) $("#options3d").dialog("close");
if (preview3d.offsetParent) $("#preview3d").dialog("close"); if (preview3d.offsetParent) $("#preview3d").dialog("close");
} }
@ -997,7 +997,7 @@ async function enter3dView(type) {
}; };
if (type === "heightmap3DView") { if (type === "heightmap3DView") {
document.getElementById("preview3d").appendChild(canvas); byId("preview3d").appendChild(canvas);
$("#preview3d").dialog({ $("#preview3d").dialog({
title: "3D Preview", title: "3D Preview",
resizable: true, resizable: true,
@ -1011,7 +1011,7 @@ async function enter3dView(type) {
} }
function resize3d() { function resize3d() {
const canvas = document.getElementById("canvas3d"); const canvas = byId("canvas3d");
canvas.width = parseFloat(preview3d.style.width); canvas.width = parseFloat(preview3d.style.width);
canvas.height = parseFloat(preview3d.style.height) - 2; canvas.height = parseFloat(preview3d.style.height) - 2;
ThreeD.redraw(); ThreeD.redraw();
@ -1034,32 +1034,32 @@ function toggle3dOptions() {
if (modules.options3d) return; if (modules.options3d) return;
modules.options3d = true; modules.options3d = true;
document.getElementById("options3dUpdate").addEventListener("click", ThreeD.update); byId("options3dUpdate").addEventListener("click", ThreeD.update);
document.getElementById("options3dSave").addEventListener("click", ThreeD.saveScreenshot); byId("options3dSave").addEventListener("click", ThreeD.saveScreenshot);
document.getElementById("options3dOBJSave").addEventListener("click", ThreeD.saveOBJ); byId("options3dOBJSave").addEventListener("click", ThreeD.saveOBJ);
document.getElementById("options3dScaleRange").addEventListener("input", changeHeightScale); byId("options3dScaleRange").addEventListener("input", changeHeightScale);
document.getElementById("options3dScaleNumber").addEventListener("change", changeHeightScale); byId("options3dScaleNumber").addEventListener("change", changeHeightScale);
document.getElementById("options3dLightnessRange").addEventListener("input", changeLightness); byId("options3dLightnessRange").addEventListener("input", changeLightness);
document.getElementById("options3dLightnessNumber").addEventListener("change", changeLightness); byId("options3dLightnessNumber").addEventListener("change", changeLightness);
document.getElementById("options3dSunX").addEventListener("change", changeSunPosition); byId("options3dSunX").addEventListener("change", changeSunPosition);
document.getElementById("options3dSunY").addEventListener("change", changeSunPosition); byId("options3dSunY").addEventListener("change", changeSunPosition);
document.getElementById("options3dMeshSkinResolution").addEventListener("change", changeResolutionScale); byId("options3dMeshSkinResolution").addEventListener("change", changeResolutionScale);
document.getElementById("options3dMeshRotationRange").addEventListener("input", changeRotation); byId("options3dMeshRotationRange").addEventListener("input", changeRotation);
document.getElementById("options3dMeshRotationNumber").addEventListener("change", changeRotation); byId("options3dMeshRotationNumber").addEventListener("change", changeRotation);
document.getElementById("options3dGlobeRotationRange").addEventListener("input", changeRotation); byId("options3dGlobeRotationRange").addEventListener("input", changeRotation);
document.getElementById("options3dGlobeRotationNumber").addEventListener("change", changeRotation); byId("options3dGlobeRotationNumber").addEventListener("change", changeRotation);
document.getElementById("options3dMeshLabels3d").addEventListener("change", toggleLabels3d); byId("options3dMeshLabels3d").addEventListener("change", toggleLabels3d);
document.getElementById("options3dMeshSkyMode").addEventListener("change", toggleSkyMode); byId("options3dMeshSkyMode").addEventListener("change", toggleSkyMode);
document.getElementById("options3dMeshSky").addEventListener("input", changeColors); byId("options3dMeshSky").addEventListener("input", changeColors);
document.getElementById("options3dMeshWater").addEventListener("input", changeColors); byId("options3dMeshWater").addEventListener("input", changeColors);
document.getElementById("options3dGlobeResolution").addEventListener("change", changeResolution); byId("options3dGlobeResolution").addEventListener("change", changeResolution);
// document.getElementById("options3dMeshWireframeMode").addEventListener("change",toggleWireframe3d); // byId("options3dMeshWireframeMode").addEventListener("change",toggleWireframe3d);
document.getElementById("options3dSunColor").addEventListener("input", changeSunColor); byId("options3dSunColor").addEventListener("input", changeSunColor);
document.getElementById("options3dSubdivide").addEventListener("change", toggle3dSubdivision); byId("options3dSubdivide").addEventListener("change", toggle3dSubdivision);
function updateValues() { function updateValues() {
const globe = document.getElementById("canvas3d").dataset.type === "viewGlobe"; const globe = byId("canvas3d").dataset.type === "viewGlobe";
options3dMesh.style.display = globe ? "none" : "block"; options3dMesh.style.display = globe ? "none" : "block";
options3dGlobe.style.display = globe ? "block" : "none"; options3dGlobe.style.display = globe ? "block" : "none";
options3dOBJSave.style.display = globe ? "none" : "inline-block"; options3dOBJSave.style.display = globe ? "none" : "inline-block";

View file

@ -11,55 +11,58 @@ function editUnits() {
position: {my: "right top", at: "right-10 top+10", of: "svg", collision: "fit"} position: {my: "right top", at: "right-10 top+10", of: "svg", collision: "fit"}
}); });
const drawBar = () => drawScaleBar(scale); const renderScaleBar = () => {
drawScaleBar(scaleBar, scale);
fitScaleBar(scaleBar, svgWidth, svgHeight);
};
// add listeners // add listeners
document.getElementById("distanceUnitInput").addEventListener("change", changeDistanceUnit); byId("distanceUnitInput").addEventListener("change", changeDistanceUnit);
document.getElementById("distanceScaleOutput").addEventListener("input", changeDistanceScale); byId("distanceScaleOutput").addEventListener("input", changeDistanceScale);
document.getElementById("distanceScaleInput").addEventListener("change", changeDistanceScale); byId("distanceScaleInput").addEventListener("change", changeDistanceScale);
document.getElementById("heightUnit").addEventListener("change", changeHeightUnit); byId("heightUnit").addEventListener("change", changeHeightUnit);
document.getElementById("heightExponentInput").addEventListener("input", changeHeightExponent); byId("heightExponentInput").addEventListener("input", changeHeightExponent);
document.getElementById("heightExponentOutput").addEventListener("input", changeHeightExponent); byId("heightExponentOutput").addEventListener("input", changeHeightExponent);
document.getElementById("temperatureScale").addEventListener("change", changeTemperatureScale); byId("temperatureScale").addEventListener("change", changeTemperatureScale);
document.getElementById("barSizeOutput").addEventListener("input", drawBar); byId("barSizeOutput").addEventListener("input", renderScaleBar);
document.getElementById("barSizeInput").addEventListener("input", drawBar); byId("barSizeInput").addEventListener("input", renderScaleBar);
document.getElementById("barLabel").addEventListener("input", drawBar); byId("barLabel").addEventListener("input", renderScaleBar);
document.getElementById("barPosX").addEventListener("input", fitScaleBar); byId("barPosX").addEventListener("input", fitScaleBar);
document.getElementById("barPosY").addEventListener("input", fitScaleBar); byId("barPosY").addEventListener("input", fitScaleBar);
document.getElementById("barBackOpacity").addEventListener("input", changeScaleBarOpacity); byId("barBackOpacity").addEventListener("input", changeScaleBarOpacity);
document.getElementById("barBackColor").addEventListener("input", changeScaleBarColor); byId("barBackColor").addEventListener("input", changeScaleBarColor);
document.getElementById("populationRateOutput").addEventListener("input", changePopulationRate); byId("populationRateOutput").addEventListener("input", changePopulationRate);
document.getElementById("populationRateInput").addEventListener("change", changePopulationRate); byId("populationRateInput").addEventListener("change", changePopulationRate);
document.getElementById("urbanizationOutput").addEventListener("input", changeUrbanizationRate); byId("urbanizationOutput").addEventListener("input", changeUrbanizationRate);
document.getElementById("urbanizationInput").addEventListener("change", changeUrbanizationRate); byId("urbanizationInput").addEventListener("change", changeUrbanizationRate);
document.getElementById("urbanDensityOutput").addEventListener("input", changeUrbanDensity); byId("urbanDensityOutput").addEventListener("input", changeUrbanDensity);
document.getElementById("urbanDensityInput").addEventListener("change", changeUrbanDensity); byId("urbanDensityInput").addEventListener("change", changeUrbanDensity);
document.getElementById("addLinearRuler").addEventListener("click", addRuler); byId("addLinearRuler").addEventListener("click", addRuler);
document.getElementById("addOpisometer").addEventListener("click", toggleOpisometerMode); byId("addOpisometer").addEventListener("click", toggleOpisometerMode);
document.getElementById("addRouteOpisometer").addEventListener("click", toggleRouteOpisometerMode); byId("addRouteOpisometer").addEventListener("click", toggleRouteOpisometerMode);
document.getElementById("addPlanimeter").addEventListener("click", togglePlanimeterMode); byId("addPlanimeter").addEventListener("click", togglePlanimeterMode);
document.getElementById("removeRulers").addEventListener("click", removeAllRulers); byId("removeRulers").addEventListener("click", removeAllRulers);
document.getElementById("unitsRestore").addEventListener("click", restoreDefaultUnits); byId("unitsRestore").addEventListener("click", restoreDefaultUnits);
function changeDistanceUnit() { function changeDistanceUnit() {
if (this.value === "custom_name") { if (this.value === "custom_name") {
prompt("Provide a custom name for a distance unit", {default: ""}, custom => { prompt("Provide a custom name for a distance unit", {default: ""}, custom => {
this.options.add(new Option(custom, custom, false, true)); this.options.add(new Option(custom, custom, false, true));
lock("distanceUnit"); lock("distanceUnit");
drawScaleBar(scale); renderScaleBar();
calculateFriendlyGridSize(); calculateFriendlyGridSize();
}); });
return; return;
} }
drawScaleBar(scale); renderScaleBar();
calculateFriendlyGridSize(); calculateFriendlyGridSize();
} }
function changeDistanceScale() { function changeDistanceScale() {
drawScaleBar(scale); renderScaleBar();
calculateFriendlyGridSize(); calculateFriendlyGridSize();
} }
@ -104,8 +107,8 @@ function editUnits() {
function restoreDefaultUnits() { function restoreDefaultUnits() {
// distanceScale // distanceScale
distanceScale = 3; distanceScale = 3;
document.getElementById("distanceScaleOutput").value = 3; byId("distanceScaleOutput").value = 3;
document.getElementById("distanceScaleInput").value = 3; byId("distanceScaleInput").value = 3;
unlock("distanceScale"); unlock("distanceScale");
// units // units
@ -139,7 +142,7 @@ function editUnits() {
localStorage.removeItem("barBackColor"); localStorage.removeItem("barBackColor");
localStorage.removeItem("barPosX"); localStorage.removeItem("barPosX");
localStorage.removeItem("barPosY"); localStorage.removeItem("barPosY");
drawScaleBar(scale); renderScaleBar();
// population // population
populationRate = populationRateOutput.value = populationRateInput.value = 1000; populationRate = populationRateOutput.value = populationRateInput.value = 1000;
@ -152,7 +155,7 @@ function editUnits() {
function addRuler() { function addRuler() {
if (!layerIsOn("toggleRulers")) toggleRulers(); if (!layerIsOn("toggleRulers")) toggleRulers();
const pt = document.getElementById("map").createSVGPoint(); const pt = byId("map").createSVGPoint();
(pt.x = graphWidth / 2), (pt.y = graphHeight / 4); (pt.x = graphWidth / 2), (pt.y = graphHeight / 4);
const p = pt.matrixTransform(viewbox.node().getScreenCTM().inverse()); const p = pt.matrixTransform(viewbox.node().getScreenCTM().inverse());
const dx = graphWidth / 4 / scale; const dx = graphWidth / 4 / scale;

View file

@ -1,7 +1,7 @@
"use strict"; "use strict";
// version and caching control // version and caching control
const version = "1.94.01"; // generator version, update each time const version = "1.94.02"; // generator version, update each time
{ {
document.title += " v" + version; document.title += " v" + version;