Files
fuesse-sexy/public/js/scene.js
Guido b95464670a Mobile-Fixes, Cover-Rendering, aufrechte Objekte, Fuss-Favicon
- Rendering von SVG-viewBox auf sauberes DOM-Modell (div#world > img) umgestellt:
  behebt den Pinch-Fokus-Bug ("zoomt in die Ecke") auf Touch
- Szene fuellt jetzt bildschirmfuellend (Cover) mit eigener Cover-Klemmung statt
  Letterbox-Balken (v.a. mobil im Hochformat)
- Tippen ueber Pointer-Events statt click (funktioniert auf Touch, wo panzoom das
  synthetische click unterdrueckt); Mehrfinger/Pinch zaehlt nie als Tipp
- touch-action:none aufs Bild -> fluessiges Pinch-Zoom
- Objekte aufrecht (leichte Neigung) statt zufaellig gekippt + dezenter Tiefen-Verlauf
  -> wirkt wie eine Szene statt "Haufen"
- Favicon: Fuss-Emoji

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-04 18:50:44 +02:00

276 lines
8.9 KiB
JavaScript

// Rendert eine Szene und liefert das "Google-Maps-Gefuehl" via panzoom.
//
// Die komplette Szene wird EINMAL in ein Bild (Canvas -> <img>) gerendert; panzoom
// bewegt/zoomt dann nur dieses eine Bild -> butterweich, egal wie viele Items.
// Aufbau bewusst als reines DOM (div#world > img) statt SVG-viewBox: so stimmt der
// Pinch-Fokuspunkt auf Touch, und die Szene fuellt den Schirm (Cover), statt in
// schwarzen Balken zu ertrinken.
const EMOJI_BASE = '/emoji/';
const TAP_THRESHOLD_PX = 12; // Bewegung darueber = Ziehen, kein Tippen
const TAP_MAX_MS = 500; // laenger gedrueckt = kein Tippen
const RENDER_SCALE = 2; // Aufloesung des Szenen-Bitmaps (Schaerfe beim Zoomen)
const EMOJI_FONT = '"Apple Color Emoji","Segoe UI Emoji","Noto Color Emoji",sans-serif';
let emojiAssetsAvailable = null; // pro Session: liegt ein Emoji-Bildset vor?
function loadImage(url) {
return new Promise((resolve) => {
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = () => resolve({ url, img });
img.onerror = () => resolve({ url, img: null });
img.src = url;
});
}
export class Scene {
constructor(stage, world, img) {
this.stage = stage;
this.world = world;
this.img = img;
this.pz = null;
this.tapHandler = null;
this._objectUrl = null;
this._imgCache = new Map();
this._w = 2000;
this._h = 1400;
this._cover = 1;
// Tippen ueber Pointer-Events (funktioniert auch auf Touch, wo panzoom das
// synthetische click-Event unterdrueckt). Pinch/Mehrfinger zaehlt nie als Tipp.
this._pointers = new Map();
this._multiTouch = false;
this.stage.addEventListener('pointerdown', (e) => {
this._pointers.set(e.pointerId, { x: e.clientX, y: e.clientY, t: performance.now() });
if (this._pointers.size > 1) this._multiTouch = true;
});
this.stage.addEventListener('pointerup', (e) => {
const down = this._pointers.get(e.pointerId);
this._pointers.delete(e.pointerId);
const wasMulti = this._multiTouch;
if (this._pointers.size === 0) this._multiTouch = false;
if (!down || wasMulti) return;
const moved = Math.hypot(e.clientX - down.x, e.clientY - down.y);
const dt = performance.now() - down.t;
if (moved > TAP_THRESHOLD_PX || dt > TAP_MAX_MS) return; // war Ziehen/Halten
this._emitTap(e.clientX, e.clientY);
});
const forget = (e) => {
this._pointers.delete(e.pointerId);
if (this._pointers.size === 0) this._multiTouch = false;
};
this.stage.addEventListener('pointercancel', forget);
// Bei Groessen-/Orientierungswechsel die Cover-Ansicht neu einpassen.
window.addEventListener('resize', () => {
if (this.pz) this._applyCover();
});
}
onTap(handler) {
this.tapHandler = handler;
}
_emitTap(clientX, clientY) {
if (!this.tapHandler || !this.pz) return;
const r = this.stage.getBoundingClientRect();
const t = this.pz.getTransform();
const x = (clientX - r.left - t.x) / t.scale;
const y = (clientY - r.top - t.y) / t.scale;
this.tapHandler({ x, y });
}
async render(payload) {
if (this.pz) {
this.pz.dispose();
this.pz = null;
}
this._w = payload.width;
this._h = payload.height;
if (payload.type === 'emoji' && emojiAssetsAvailable === null) {
const sample = payload.items.find((i) => i.kind === 'emoji');
emojiAssetsAvailable = sample
? (await loadImage(EMOJI_BASE + sample.codepoint + '.png')).img !== null
: false;
}
await this._preloadAssets(payload);
const url = await this._rasterize(payload);
if (this._objectUrl) URL.revokeObjectURL(this._objectUrl);
this._objectUrl = url;
// Bild sicher laden, bevor wir einpassen (getBoundingClientRect etc.)
await new Promise((res) => {
this.img.onload = res;
this.img.onerror = res;
this.img.src = url;
});
this.world.style.width = this._w + 'px';
this.world.style.height = this._h + 'px';
this._initPanzoom();
}
async _preloadAssets(payload) {
const urls = new Set();
for (const it of payload.items) {
if (it.kind === 'image') urls.add(it.assetUrl);
else if (it.kind === 'emoji' && emojiAssetsAvailable) urls.add(EMOJI_BASE + it.codepoint + '.png');
}
const missing = [...urls].filter((u) => !this._imgCache.has(u));
const loaded = await Promise.all(missing.map(loadImage));
for (const { url, img } of loaded) this._imgCache.set(url, img);
}
async _rasterize(payload) {
const canvas = document.createElement('canvas');
canvas.width = payload.width * RENDER_SCALE;
canvas.height = payload.height * RENDER_SCALE;
const ctx = canvas.getContext('2d');
ctx.scale(RENDER_SCALE, RENDER_SCALE);
// Basisfarbe + dezenter Tiefen-Verlauf (oben heller, unten leichter Schatten)
ctx.fillStyle = payload.background || '#ffffff';
ctx.fillRect(0, 0, payload.width, payload.height);
const grad = ctx.createLinearGradient(0, 0, 0, payload.height);
grad.addColorStop(0, 'rgba(255,255,255,0.22)');
grad.addColorStop(0.5, 'rgba(255,255,255,0)');
grad.addColorStop(1, 'rgba(0,0,0,0.14)');
ctx.fillStyle = grad;
ctx.fillRect(0, 0, payload.width, payload.height);
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
for (const item of payload.items) {
ctx.save();
ctx.translate(item.cx, item.cy);
ctx.rotate((item.rot * Math.PI) / 180);
this._drawItem(ctx, item);
ctx.restore();
}
return await new Promise((resolve) => {
canvas.toBlob((blob) => resolve(URL.createObjectURL(blob)), 'image/png');
});
}
_drawItem(ctx, item) {
const size = item.size;
if (item.kind === 'emoji' && !emojiAssetsAvailable) {
ctx.font = `${size}px ${EMOJI_FONT}`;
ctx.fillText(item.glyph, 0, 0);
return;
}
const url = item.kind === 'image' ? item.assetUrl : EMOJI_BASE + item.codepoint + '.png';
const img = this._imgCache.get(url);
if (!img) {
if (item.kind === 'emoji') {
ctx.font = `${size}px ${EMOJI_FONT}`;
ctx.fillText(item.glyph, 0, 0);
}
return;
}
const isSvg = url.toLowerCase().endsWith('.svg');
let dw = size;
let dh = size;
if (!isSvg && img.naturalWidth && img.naturalHeight) {
const s = Math.min(size / img.naturalWidth, size / img.naturalHeight);
dw = img.naturalWidth * s;
dh = img.naturalHeight * s;
}
ctx.drawImage(img, -dw / 2, -dh / 2, dw, dh);
}
_coverScale() {
const r = this.stage.getBoundingClientRect();
return Math.max(r.width / this._w, r.height / this._h);
}
_initPanzoom() {
this._cover = this._coverScale();
if (typeof panzoom === 'function') {
this.pz = panzoom(this.world, {
maxZoom: this._cover * 9,
minZoom: this._cover, // nicht weiter raus als "Cover"
smoothScroll: true,
zoomDoubleClickSpeed: 1,
});
// Eigene Cover-Klemmung: das Bild deckt den Schirm immer voll (kein Leerraum).
this._clamping = false;
this.pz.on('transform', () => this._clampToCover());
}
this._applyCover();
}
// Szene bildschirmfuellend zentrieren (Cover).
_applyCover() {
if (!this.pz) return;
const r = this.stage.getBoundingClientRect();
this._cover = this._coverScale();
this.pz.zoomAbs(0, 0, this._cover);
const tx = (r.width - this._w * this._cover) / 2;
const ty = (r.height - this._h * this._cover) / 2;
this.pz.moveTo(tx, ty);
}
// Haelt die Translation so, dass das Bild den Viewport immer vollstaendig deckt.
_clampToCover() {
if (!this.pz || this._clamping) return;
const r = this.stage.getBoundingClientRect();
const t = this.pz.getTransform();
const w = this._w * t.scale;
const h = this._h * t.scale;
let x = t.x;
let y = t.y;
x = w >= r.width ? Math.min(0, Math.max(r.width - w, x)) : (r.width - w) / 2;
y = h >= r.height ? Math.min(0, Math.max(r.height - h, y)) : (r.height - h) / 2;
if (Math.abs(x - t.x) > 0.5 || Math.abs(y - t.y) > 0.5) {
this._clamping = true; // Rekursion durch das erneute transform-Event vermeiden
this.pz.moveTo(x, y);
this._clamping = false;
}
}
_stageCenterClient() {
const r = this.stage.getBoundingClientRect();
return { x: r.left + r.width / 2, y: r.top + r.height / 2 };
}
zoomIn() {
if (!this.pz) return;
const c = this._stageCenterClient();
this.pz.smoothZoom(c.x, c.y, 1.6);
}
zoomOut() {
if (!this.pz) return;
const c = this._stageCenterClient();
this.pz.smoothZoom(c.x, c.y, 0.625);
}
resetView() {
this._applyCover();
}
// kurze Treffer-/Daneben-Animation an einer Szenen-Position (Welt-Pixel)
pingAt(x, y, ok) {
const ping = document.createElement('div');
ping.className = 'ping ' + (ok ? 'ping-ok' : 'ping-miss');
ping.style.left = x + 'px';
ping.style.top = y + 'px';
this.world.appendChild(ping);
setTimeout(() => ping.remove(), 650);
}
}