LuminaWebsite/assets/map/js/views/MapView.js
Maaxxs eae0dc381e Karte: Pets einzeln als erledigt abhaken (Popup am Pet-Symbol), erledigte blass mit Haken oder ausgeblendet
Ein Pet gilt an allen Fundorten auf allen Karten als erledigt (Kennung = Symbol-Datei). Gespeichert je Konto
in map_pets_done ueber map_pets_api.php (Recht map.view). Pet-Kategorien zeigen erledigt/gesamt,
Schalter "Erledigte Pets ausblenden". Patchnotes, Datenauskunft und Datenschutz ergaenzt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-09 07:21:59 +02:00

684 lines
No EOL
26 KiB
JavaScript

/**
* MapView - Handles all canvas rendering for the map viewer
*/
class MapView {
constructor(canvas) {
this.canvas = canvas;
this.ctx = canvas.getContext('2d');
// View state
this.zoom = CONFIG.MIN_ZOOM + 1;
// Hoechste Zoomstufe der aktuellen Karte - MapController.loadMap setzt sie aus dem
// Kachel-Manifest (manche Karten haben nur Kacheln bis Stufe 5).
this.maxZoom = CONFIG.MAX_ZOOM;
// Kacheln gibt es nur in ganzen Stufen; Dungeon-Karten (ein Bild) und leere Arenen zoomen feiner.
this.zoomStep = 1;
// Ausschnitt [x0, y0, x1, y1], auf den "Ansicht zuruecksetzen" zoomt (Dungeon-Karten), sonst null
this.fitBounds = null;
// Geladene Kartenbilder der Dungeon-Karten: Slug -> Image
this.images = new Map();
this.centerWorldX = (CONFIG.WORLD_MIN_X + CONFIG.WORLD_MAX_X) / 2;
this.centerWorldY = (CONFIG.WORLD_MIN_Y + CONFIG.WORLD_MAX_Y) / 2;
// Icon cache
this.iconCache = {};
this.loadingIcons = new Map(); // Dateiname -> Promise des laufenden Ladens
// Icons, die nicht geladen werden konnten - nicht bei jedem Neuzeichnen wieder anfragen,
// sondern gleich das Emoji zeichnen.
this.failedIcons = new Set();
// Interaction state
this.isDragging = false;
this.lastMouseX = 0;
this.lastMouseY = 0;
this.renderRequested = false;
}
/**
* Resize canvas to fill window
*/
resize() {
this.canvas.width = window.innerWidth;
this.canvas.height = window.innerHeight;
// Anderes Seitenverhaeltnis (z.B. Handy gedreht): Ansicht wieder in die Karte holen
this.clampView();
}
/**
* Convert world coordinates to screen coordinates
*/
worldToScreen(worldX, worldY) {
const worldWidth = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X;
const zoomScale = Math.pow(2, this.zoom - CONFIG.MIN_ZOOM);
const visibleWidth = worldWidth / zoomScale;
const scale = this.canvas.width / visibleWidth;
const camOffsetX = -this.centerWorldX * scale + this.canvas.width / 2;
const camOffsetY = -this.centerWorldY * scale + this.canvas.height / 2;
return {
x: worldX * scale + camOffsetX,
y: worldY * scale + camOffsetY
};
}
/**
* Convert screen coordinates to world coordinates
*/
screenToWorld(screenX, screenY) {
const worldWidth = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X;
const zoomScale = Math.pow(2, this.zoom - CONFIG.MIN_ZOOM);
const visibleWidth = worldWidth / zoomScale;
const scale = this.canvas.width / visibleWidth;
const camOffsetX = -this.centerWorldX * scale + this.canvas.width / 2;
const camOffsetY = -this.centerWorldY * scale + this.canvas.height / 2;
return {
x: (screenX - camOffsetX) / scale,
y: (screenY - camOffsetY) / scale
};
}
/**
* Get viewport bounds in world coordinates
*/
getViewBounds() {
const topLeft = this.screenToWorld(0, 0);
const bottomRight = this.screenToWorld(this.canvas.width, this.canvas.height);
return {
minX: Math.min(topLeft.x, bottomRight.x),
maxX: Math.max(topLeft.x, bottomRight.x),
minY: Math.min(topLeft.y, bottomRight.y),
maxY: Math.max(topLeft.y, bottomRight.y)
};
}
/**
* Render the map with tiles and markers
*/
async render(tileService, mapData) {
const ctx = this.ctx;
const width = this.canvas.width;
const height = this.canvas.height;
// Clear canvas
ctx.fillStyle = '#0a0a1e';
ctx.fillRect(0, 0, width, height);
// Zeichenebene der Taktiken sofort mitziehen, nicht erst nach dem Laden der Kacheln.
if (this.onViewChange) this.onViewChange();
// Pin eines geteilten Ortes mitziehen (LocationController)
if (this.onPinUpdate) this.onPinUpdate();
if (!mapData.currentMap) return;
// Dungeon-Karten sind ein einzelnes Bild, leere Arenen werden gezeichnet - beides ohne Kacheln und Marker
if (mapData.currentMap.kind === 'image') {
this.drawImageMap(mapData.currentMap);
return;
}
if (mapData.currentMap.kind === 'arena') {
MapView.drawArena(ctx, mapData.currentMap.arena, (x, y) => this.worldToScreen(x, y), this.worldScale());
return;
}
const slug = mapData.currentMap.slug;
const worldWidth = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X;
// Calculate scale and camera offset
const zoomScale = Math.pow(2, this.zoom - CONFIG.MIN_ZOOM);
const visibleWidth = worldWidth / zoomScale;
const scale = width / visibleWidth;
const camOffsetX = -this.centerWorldX * scale + width / 2;
const camOffsetY = -this.centerWorldY * scale + height / 2;
// Aendert sich die Ansicht, waehrend dieses Bild noch auf Kacheln oder Icons wartet, hoert
// es auf (sonst landen Kacheln und Marker an der alten Stelle ueber dem neuen Bild).
const isStale = this.staleCheck(tileService, mapData);
// Draw tiles at current zoom level
const tilesPerSide = Math.pow(2, this.zoom);
const tileWorldSize = worldWidth / tilesPerSide;
const tileScreenSize = tileWorldSize * scale;
for (let tx = 0; tx < tilesPerSide; tx++) {
for (let ty = 0; ty < tilesPerSide; ty++) {
// World position of this tile's top-left corner
const tileWorldX = CONFIG.WORLD_MIN_X + tx * tileWorldSize;
const tileWorldY = CONFIG.WORLD_MIN_Y + ty * tileWorldSize;
// Screen position after camera transform
const screenX = tileWorldX * scale + camOffsetX;
const screenY = tileWorldY * scale + camOffsetY;
// Skip tiles completely outside viewport (with margin)
if (screenX + tileScreenSize < -tileScreenSize ||
screenX > width + tileScreenSize ||
screenY + tileScreenSize < -tileScreenSize ||
screenY > height + tileScreenSize) {
continue;
}
const tileImg = await tileService.loadTile(slug, this.zoom, tx, ty);
if (isStale()) return;
if (tileImg) {
ctx.drawImage(tileImg, screenX, screenY, tileScreenSize, tileScreenSize);
} else {
// Placeholder for missing/loading tiles
ctx.fillStyle = '#1a1a3e';
ctx.fillRect(screenX, screenY, tileScreenSize, tileScreenSize);
}
}
}
// Draw markers
this.drawMarkers(mapData, isStale);
// Preload adjacent zoom levels in background
const viewBounds = this.getViewBounds();
tileService.preloadAdjacentZoomLevels(slug, this.zoom, viewBounds);
}
/**
* Kartenbild einer Dungeon-Karte laden (dungeons/<slug>.webp). Liefert das Bild oder null,
* wenn es fehlt - dann zeigt die Karte einen Hinweis statt des Bildes.
*/
loadMapImage(map) {
const cached = this.images.get(map.slug);
if (cached) return Promise.resolve(cached);
return new Promise(resolve => {
const img = new Image();
img.onload = () => {
// Nur das aktuelle Bild behalten - entpackt sind es je 16 MB Speicher
this.images.clear();
this.images.set(map.slug, img);
resolve(img);
};
img.onerror = () => resolve(null);
img.src = `${CONFIG.DUNGEONS_DIR}/${map.slug}.webp${map.version ? '?v=' + map.version : ''}`;
});
}
/**
* Wo ein Kartenbild in der Welt liegt: so gross wie moeglich im Quadrat 0..4096, mittig - wie in
* scripts/download_dungeon_maps.py (world_bounds), damit dessen Ausschnitte passen.
*/
static imageRect(width, height) {
const worldSize = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X;
const scale = worldSize / Math.max(width, height);
return {
x: CONFIG.WORLD_MIN_X + (worldSize - width * scale) / 2,
y: CONFIG.WORLD_MIN_Y + (worldSize - height * scale) / 2,
w: width * scale,
h: height * scale
};
}
/** Dungeon-Karte: nur den sichtbaren Teil des Bildes zeichnen (weich vergroessert). */
drawImageMap(map) {
const ctx = this.ctx;
// Farbe des Bildrands - herausgezoomt geht die Karte so ohne Kante in den Hintergrund ueber
ctx.fillStyle = '#0c1214';
ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
const img = this.images.get(map.slug);
if (!img) {
ctx.fillStyle = '#aaaaaa';
ctx.font = "14px 'Segoe UI', sans-serif";
ctx.textAlign = 'center';
ctx.fillText('Das Kartenbild fehlt noch (assets/map/dungeons).', this.canvas.width / 2, this.canvas.height / 2);
return;
}
const rect = MapView.imageRect(img.naturalWidth, img.naturalHeight);
const view = this.getViewBounds();
const x0 = Math.max(rect.x, view.minX);
const y0 = Math.max(rect.y, view.minY);
const x1 = Math.min(rect.x + rect.w, view.maxX);
const y1 = Math.min(rect.y + rect.h, view.maxY);
if (x1 <= x0 || y1 <= y0) return;
const texels = img.naturalWidth / rect.w;
const from = this.worldToScreen(x0, y0);
const to = this.worldToScreen(x1, y1);
ctx.imageSmoothingEnabled = true;
ctx.imageSmoothingQuality = 'high';
ctx.drawImage(img, (x0 - rect.x) * texels, (y0 - rect.y) * texels, (x1 - x0) * texels, (y1 - y0) * texels,
from.x, from.y, to.x - from.x, to.y - from.y);
}
/** Ausschnitt einer leeren Arena (mit Platz fuer die Himmelsrichtungen). */
static arenaBounds() {
const c = (CONFIG.WORLD_MIN_X + CONFIG.WORLD_MAX_X) / 2;
const r = CONFIG.ARENA_RADIUS * 1.3;
return [c - r, c - r, c + r, c + r];
}
/**
* Leere Arena (rund oder eckig) zeichnen: Boden mit Hilfslinien, Rand, Himmelsrichtungen.
* toScreen(x, y) rechnet Welt- in Bildschirmkoordinaten um, scale = Pixel je Welteinheit.
*/
static drawArena(ctx, shape, toScreen, scale) {
const c = (CONFIG.WORLD_MIN_X + CONFIG.WORLD_MAX_X) / 2;
const center = toScreen(c, c);
const r = CONFIG.ARENA_RADIUS * scale;
const line = 'rgba(160, 180, 230, 0.13)';
const gold = 'rgba(255, 215, 0, 0.65)';
ctx.save();
ctx.fillStyle = '#0b0f1c';
ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);
const floor = ctx.createRadialGradient(center.x, center.y, r * 0.1, center.x, center.y, r * 1.2);
floor.addColorStop(0, '#23304f');
floor.addColorStop(1, '#141b2f');
ctx.fillStyle = floor;
ctx.strokeStyle = line;
ctx.lineWidth = 1;
if (shape === 'square') {
ctx.fillRect(center.x - r, center.y - r, r * 2, r * 2);
// Raster in Achteln, die Mittellinien etwas deutlicher
for (let i = 1; i < 8; i++) {
const offset = -r + (r * 2 * i) / 8;
ctx.strokeStyle = i === 4 ? 'rgba(160, 180, 230, 0.26)' : line;
ctx.beginPath();
ctx.moveTo(center.x + offset, center.y - r);
ctx.lineTo(center.x + offset, center.y + r);
ctx.moveTo(center.x - r, center.y + offset);
ctx.lineTo(center.x + r, center.y + offset);
ctx.stroke();
}
ctx.lineWidth = 2.5;
ctx.strokeStyle = '#8fa3d6';
ctx.strokeRect(center.x - r, center.y - r, r * 2, r * 2);
} else {
ctx.beginPath();
ctx.arc(center.x, center.y, r, 0, Math.PI * 2);
ctx.fill();
// Ringe bei einem und zwei Dritteln, Speichen wie die Stunden einer Uhr
[1 / 3, 2 / 3].forEach(part => {
ctx.beginPath();
ctx.arc(center.x, center.y, r * part, 0, Math.PI * 2);
ctx.stroke();
});
for (let i = 0; i < 12; i++) {
const angle = i * Math.PI / 6;
ctx.strokeStyle = i % 3 === 0 ? 'rgba(160, 180, 230, 0.26)' : line;
ctx.beginPath();
ctx.moveTo(center.x, center.y);
ctx.lineTo(center.x + Math.sin(angle) * r, center.y - Math.cos(angle) * r);
ctx.stroke();
// Stundenstriche aussen
ctx.strokeStyle = gold;
ctx.lineWidth = i % 3 === 0 ? 2.5 : 1.5;
const inner = r + 4;
const outer = r + (i % 3 === 0 ? 16 : 10);
ctx.beginPath();
ctx.moveTo(center.x + Math.sin(angle) * inner, center.y - Math.cos(angle) * inner);
ctx.lineTo(center.x + Math.sin(angle) * outer, center.y - Math.cos(angle) * outer);
ctx.stroke();
ctx.lineWidth = 1;
}
ctx.lineWidth = 2.5;
ctx.strokeStyle = '#8fa3d6';
ctx.beginPath();
ctx.arc(center.x, center.y, r, 0, Math.PI * 2);
ctx.stroke();
}
// Mitte
ctx.strokeStyle = 'rgba(255, 255, 255, 0.35)';
ctx.lineWidth = 1.5;
ctx.beginPath();
ctx.moveTo(center.x - 7, center.y);
ctx.lineTo(center.x + 7, center.y);
ctx.moveTo(center.x, center.y - 7);
ctx.lineTo(center.x, center.y + 7);
ctx.stroke();
// Himmelsrichtungen
const size = Math.max(11, Math.min(18, r * 0.07));
const distance = r + 16 + size;
ctx.font = `bold ${Math.round(size)}px 'Segoe UI', sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillStyle = gold;
[['N', 0, -1], ['O', 1, 0], ['S', 0, 1], ['W', -1, 0]].forEach(([label, dx, dy]) => {
ctx.fillText(label, center.x + dx * distance, center.y + dy * distance);
});
ctx.restore();
}
/** Vorschaubild einer leeren Arena fuer die Kartenauswahl (Daten-URL). */
static arenaPreview(shape, size = 320) {
const canvas = document.createElement('canvas');
canvas.width = size;
canvas.height = size;
// Etwas mehr Rand als auf der Karte - im kleinen Bild brauchen die Himmelsrichtungen mehr Platz
const c = (CONFIG.WORLD_MIN_X + CONFIG.WORLD_MAX_X) / 2;
const half = CONFIG.ARENA_RADIUS * 1.45;
const x0 = c - half;
const y0 = c - half;
const scale = size / (half * 2);
MapView.drawArena(canvas.getContext('2d'), shape, (x, y) => ({ x: (x - x0) * scale, y: (y - y0) * scale }), scale);
return canvas.toDataURL('image/png');
}
/**
* Prueft fuer ein laufendes Bild, ob sich die Ansicht (Karte, Zoom, Position, Groesse) seit
* seinem Start geaendert hat. Dann ist es veraltet und stoesst einmal ein frisches Bild an -
* so erscheint, was es gerade fertig geladen hat, trotzdem an der richtigen Stelle.
* Ein Kartenwechsel zeichnet loadMap selbst neu, sobald die neue Karte geladen ist.
*/
staleCheck(tileService, mapData) {
const map = mapData.currentMap;
const zoom = this.zoom;
const centerX = this.centerWorldX;
const centerY = this.centerWorldY;
const width = this.canvas.width;
const height = this.canvas.height;
let stale = false;
return () => {
if (stale) return true;
if (mapData.currentMap === map && this.zoom === zoom
&& this.centerWorldX === centerX && this.centerWorldY === centerY
&& this.canvas.width === width && this.canvas.height === height) {
return false;
}
stale = true;
if (mapData.currentMap === map) this.requestRender(tileService, mapData);
return true;
};
}
/**
* Load an icon image from local data directory
*/
async loadIcon(iconPath) {
if (!iconPath) return null;
// Extract filename from path
const filename = iconPath.split('/').pop();
if (this.iconCache[filename]) {
return this.iconCache[filename];
}
// Datei fehlt oder ist kaputt: nicht erneut anfragen, gleich das Emoji zeichnen
if (this.failedIcons.has(filename)) {
return null;
}
// Laedt schon (z.B. fuer ein frueheres Bild): auf dasselbe Laden warten
if (this.loadingIcons.has(filename)) {
return this.loadingIcons.get(filename);
}
const loading = new Promise(resolve => {
const img = new Image();
// Langsam: vorerst das Emoji - kommt das Bild spaeter doch noch, nimmt es das naechste Bild
const timer = setTimeout(() => resolve(null), 3000);
img.onload = () => {
clearTimeout(timer);
this.iconCache[filename] = img;
resolve(img);
};
img.onerror = () => {
clearTimeout(timer);
this.failedIcons.add(filename);
resolve(null);
};
img.src = `${CONFIG.ICONS_DIR}/${filename}`;
});
this.loadingIcons.set(filename, loading);
loading.then(() => this.loadingIcons.delete(filename));
return loading;
}
/**
* Draw all visible markers using icon images
*/
async drawMarkers(mapData, isStale = () => false) {
const ctx = this.ctx;
for (const marker of mapData.markers) {
if (!mapData.isMarkerShown(marker)) continue;
const iconSize = this.markerSize();
// Erledigte Pets blass und mit Haken
const done = mapData.isPetDone(marker);
// Try to load and draw icon image
let iconImg = null;
if (marker.iconImage) {
iconImg = await this.loadIcon(marker.iconImage);
// Ansicht hat sich beim Warten geaendert: nicht an der alten Stelle weiterzeichnen
if (isStale()) return;
}
// Position erst nach dem Warten bestimmen
const screen = this.worldToScreen(marker.worldX, marker.worldY);
if (done) ctx.globalAlpha = 0.4;
if (iconImg) {
// Draw icon image centered at marker position
ctx.drawImage(iconImg,
screen.x - iconSize / 2,
screen.y - iconSize / 2,
iconSize,
iconSize);
} else {
// Fallback to emoji if no icon available
const symbol = CONFIG.CATEGORY_SYMBOLS[marker.category_name] || '📍';
const fontSize = Math.round(iconSize * 0.75);
ctx.font = `${fontSize}px sans-serif`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(symbol, screen.x, screen.y);
}
if (done) {
ctx.globalAlpha = 1;
MapView.drawDoneBadge(ctx, screen.x + iconSize * 0.32, screen.y + iconSize * 0.32, Math.max(6, iconSize * 0.24));
}
}
}
/** Gruener Kreis mit Haken (erledigtes Pet) */
static drawDoneBadge(ctx, x, y, r) {
ctx.save();
ctx.beginPath();
ctx.arc(x, y, r, 0, Math.PI * 2);
ctx.fillStyle = '#3fa34d';
ctx.fill();
ctx.lineWidth = 1.5;
ctx.strokeStyle = '#0a0a1e';
ctx.stroke();
ctx.beginPath();
ctx.moveTo(x - r * 0.45, y + r * 0.02);
ctx.lineTo(x - r * 0.1, y + r * 0.38);
ctx.lineTo(x + r * 0.5, y - r * 0.35);
ctx.lineWidth = Math.max(1.5, r * 0.3);
ctx.strokeStyle = '#fff';
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.stroke();
ctx.restore();
}
/**
* Groesse der Marker-Icons in Pixeln - waechst mit der Zoomstufe, damit man sie auch
* herausgezoomt noch erkennt.
*/
markerSize() {
const sizes = { 2: 20, 3: 24, 4: 28, 5: 32, 6: 38 };
return sizes[this.zoom] || (this.zoom < 2 ? 18 : 38);
}
/**
* Zoom in
*/
zoomIn() {
// Nur bis zur hoechsten Stufe dieser Karte - darueber gibt es keine Kacheln
if (this.zoom + this.zoomStep <= this.maxZoom + 1e-9) {
this.zoom += this.zoomStep;
this.clampView();
return true;
}
return false;
}
/**
* Zoom out
*/
zoomOut() {
if (this.zoom - this.zoomStep >= CONFIG.MIN_ZOOM - 1e-9) {
this.zoom -= this.zoomStep;
this.clampView();
return true;
}
return false;
}
/**
* Eine Stufe rein (+1) oder raus (-1) zoomen, wobei der Weltpunkt unter
* screenX/screenY an seiner Stelle bleibt (z.B. zwischen zwei Fingern).
*/
zoomAt(step, screenX, screenY) {
const before = this.screenToWorld(screenX, screenY);
const changed = step > 0 ? this.zoomIn() : this.zoomOut();
if (!changed) return false;
const after = this.screenToWorld(screenX, screenY);
const scale = this.worldToScreen(1, 0).x - this.worldToScreen(0, 0).x;
this.panBy((after.x - before.x) * scale, (after.y - before.y) * scale);
return true;
}
/**
* Reset view to default
*/
resetView() {
if (this.fitBounds && this.canvas.width && this.canvas.height) {
this.fitTo(this.fitBounds);
return;
}
this.zoom = Math.min(CONFIG.MIN_ZOOM + 1, this.maxZoom);
this.centerWorldX = (CONFIG.WORLD_MIN_X + CONFIG.WORLD_MAX_X) / 2;
this.centerWorldY = (CONFIG.WORLD_MIN_Y + CONFIG.WORLD_MAX_Y) / 2;
this.clampView();
}
/**
* Den Ausschnitt [x0, y0, x1, y1] (Weltkoordinaten) moeglichst gross zeigen: die groesste
* Zoomstufe, in die er ganz passt - mit etwas Rand fuer die Fenster ueber der Karte.
*/
fitTo(bounds) {
const [x0, y0, x1, y1] = bounds;
const worldWidth = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X;
const width = Math.max(1, x1 - x0);
const height = Math.max(1, y1 - y0);
// Rechts liegen Taktik-Panel und Zoomleiste ueber der Karte - auf breiten Bildschirmen den Platz
// daneben nutzen (auf dem Handy liegen die Fenster eingeklappt oben).
const reserved = this.canvas.width > 900 ? 380 : 0;
const usable = this.canvas.width - reserved;
// Bildschirmpixel je Welteinheit bei Stufe z: canvas.width * 2^(z - MIN_ZOOM) / worldWidth
const fitX = Math.log2(0.92 * usable * worldWidth / (width * this.canvas.width));
const fitY = Math.log2(0.82 * this.canvas.height * worldWidth / (height * this.canvas.width));
const zoom = CONFIG.MIN_ZOOM + Math.floor(Math.min(fitX, fitY) / this.zoomStep) * this.zoomStep;
this.zoom = Math.max(CONFIG.MIN_ZOOM, Math.min(this.maxZoom, zoom));
this.centerWorldX = (x0 + x1) / 2 + reserved / 2 / this.worldScale();
this.centerWorldY = (y0 + y1) / 2;
this.clampView();
}
/**
* Pan by screen delta
*/
panBy(dx, dy) {
const scale = this.worldScale();
if (!scale) return;
// Each screen pixel represents 1/scale world units
const worldDx = -(dx / scale);
const worldDy = -(dy / scale);
this.centerWorldX += worldDx;
this.centerWorldY += worldDy;
// Nicht ueber den Kartenrand hinaus ziehen
this.clampView();
}
/**
* Bildschirmpixel pro Welteinheit bei der aktuellen Zoomstufe
*/
worldScale() {
const worldWidth = CONFIG.WORLD_MAX_X - CONFIG.WORLD_MIN_X;
const visibleWidth = worldWidth / Math.pow(2, this.zoom - CONFIG.MIN_ZOOM);
return this.canvas.width / visibleWidth;
}
/**
* Ansicht in der Karte halten: Ist der sichtbare Bereich auf einer Achse groesser als die Karte
* (z.B. Handy hochkant ganz herausgezoomt), steht die Karte auf dieser Achse mittig; sonst
* bleiben die Raender der Ansicht innerhalb der Karte - kein Ziehen ins Leere.
*/
clampView() {
const scale = this.worldScale();
// Noch ohne Groesse (z.B. Rahmen unsichtbar): nichts zu begrenzen
if (!scale || !this.canvas.height) return;
const clampAxis = (center, min, max, halfVisible) => {
if (!isFinite(center) || max - min <= halfVisible * 2) return (min + max) / 2;
return Math.min(max - halfVisible, Math.max(min + halfVisible, center));
};
this.centerWorldX = clampAxis(this.centerWorldX, CONFIG.WORLD_MIN_X, CONFIG.WORLD_MAX_X,
this.canvas.width / scale / 2);
this.centerWorldY = clampAxis(this.centerWorldY, CONFIG.WORLD_MIN_Y, CONFIG.WORLD_MAX_Y,
this.canvas.height / scale / 2);
}
/**
* Request a render frame
*/
requestRender(tileService, mapData) {
if (!this.renderRequested) {
this.renderRequested = true;
requestAnimationFrame(() => {
this.render(tileService, mapData);
this.renderRequested = false;
});
}
}
/**
* Find nearest marker to screen position
*/
findNearestMarker(mapData, screenX, screenY, threshold = this.markerSize() * 0.7) {
let nearest = null;
let nearestDist = threshold;
for (const marker of mapData.markers) {
if (!mapData.isMarkerShown(marker)) continue;
const screen = this.worldToScreen(marker.worldX, marker.worldY);
const dx = screenX - screen.x;
const dy = screenY - screen.y;
const dist = Math.sqrt(dx * dx + dy * dy);
if (dist < nearestDist) {
nearestDist = dist;
nearest = marker;
}
}
return nearest;
}
}