59 lines
1.7 KiB
TypeScript
59 lines
1.7 KiB
TypeScript
// Pan/zoom of the canvas view. World units are PDF points.
|
|
|
|
import type { Rect } from '$lib/model/layout';
|
|
|
|
export const MIN_SCALE = 0.04;
|
|
export const MAX_SCALE = 8;
|
|
|
|
class Viewport {
|
|
/** Screen position of the world origin, in CSS px. */
|
|
x = $state(0);
|
|
y = $state(0);
|
|
scale = $state(1);
|
|
/** Size of the stage element. */
|
|
width = $state(0);
|
|
height = $state(0);
|
|
|
|
toWorld(sx: number, sy: number) {
|
|
return { x: (sx - this.x) / this.scale, y: (sy - this.y) / this.scale };
|
|
}
|
|
|
|
toScreen(wx: number, wy: number) {
|
|
return { x: wx * this.scale + this.x, y: wy * this.scale + this.y };
|
|
}
|
|
|
|
/** The visible world rectangle. */
|
|
get world(): Rect {
|
|
return { x: -this.x / this.scale, y: -this.y / this.scale, width: this.width / this.scale, height: this.height / this.scale };
|
|
}
|
|
|
|
zoomAt(factor: number, sx = this.width / 2, sy = this.height / 2) {
|
|
const next = Math.min(MAX_SCALE, Math.max(MIN_SCALE, this.scale * factor));
|
|
const w = this.toWorld(sx, sy);
|
|
this.scale = next;
|
|
this.x = sx - w.x * next;
|
|
this.y = sy - w.y * next;
|
|
}
|
|
|
|
panBy(dx: number, dy: number) {
|
|
this.x += dx;
|
|
this.y += dy;
|
|
}
|
|
|
|
/** Fit a world rectangle into the stage with some padding. */
|
|
fit(r: Rect, pad = 24) {
|
|
if (!this.width || !this.height) return;
|
|
const s = Math.min((this.width - 2 * pad) / r.width, (this.height - 2 * pad) / r.height);
|
|
this.scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, s));
|
|
this.x = this.width / 2 - (r.x + r.width / 2) * this.scale;
|
|
this.y = this.height / 2 - (r.y + r.height / 2) * this.scale;
|
|
}
|
|
|
|
/** Pan so the rectangle is centred, keeping the zoom. */
|
|
center(r: Rect) {
|
|
this.x = this.width / 2 - (r.x + r.width / 2) * this.scale;
|
|
this.y = this.height / 2 - (r.y + r.height / 2) * this.scale;
|
|
}
|
|
}
|
|
|
|
export const viewport = new Viewport();
|