示例工程 30-multi-window-state
30-multi-window-state/app/shared/bounds.ts
export type Rect = { x: number; y: number; width: number; height: number };
export function intersectionArea(a: Rect, b: Rect): number {
const left = Math.max(a.x, b.x);
const top = Math.max(a.y, b.y);
const right = Math.min(a.x + a.width, b.x + b.width);
const bottom = Math.min(a.y + a.height, b.y + b.height);
if (right <= left || bottom <= top) return 0;
return (right - left) * (bottom - top);
}
export function pickArea(bounds: Rect, areas: Rect[]): Rect {
let best = areas[0];
let bestArea = -1;
for (const area of areas) {
const overlap = intersectionArea(bounds, area);
if (overlap > bestArea) {
best = area;
bestArea = overlap;
}
}
return (
best ?? {
x: 0,
y: 0,
width: 1280,
height: 800,
}
);
}
export function clampToArea(
bounds: Rect,
area: Rect,
minWidth = 320,
minHeight = 240,
): Rect {
const width = Math.min(Math.max(bounds.width, minWidth), area.width);
const height = Math.min(Math.max(bounds.height, minHeight), area.height);
return {
x: Math.min(Math.max(bounds.x, area.x), area.x + area.width - width),
y: Math.min(Math.max(bounds.y, area.y), area.y + area.height - height),
width,
height,
};
}