Skip to content

The open source AI video agent: turns any coding agent into a video agent, with an editor to change anything it makes.

Studio: fit a new canvas to what the film shows; plainer ratio menu (#24)

riverisbuildingf91edd315198
diff --git a/.changeset/canvas-fit-content.md b/.changeset/canvas-fit-content.md
new file mode 100644
index 0000000..e8d801a
--- /dev/null
+++ b/.changeset/canvas-fit-content.md
@@ -0,0 +1,6 @@
+---
+"openfilm": patch
+---
+
+Studio: changing the canvas's shape fits what the film shows to the new canvas, centered, with at least one side meeting its edge. Shapes picked one after another no longer shrink the film further each time, and a film already shrunk grows back to the edge on the next change.
+The ratio menu lists plain ratios (and 21:9), with "Original" first and nothing else, and the inspector drops its note about the canvas. A project opens with the media, the viewer, the inspector and the timeline shown, and the layers hidden.
diff --git a/packages/openfilm/studio/ui/src/components/FilmInspector.tsx b/packages/openfilm/studio/ui/src/components/FilmInspector.tsx
index 826be35..5c0a051 100644
--- a/packages/openfilm/studio/ui/src/components/FilmInspector.tsx
+++ b/packages/openfilm/studio/ui/src/components/FilmInspector.tsx
@@ -400,7 +400,6 @@ function FilmPanel({
<NumField label={t('inspector.width')} prefix="W" value={stage.w} unit="px" min={2} max={8192} disabled={!canvas} onCommit={(w) => setSize(w, stage.h)} />
<NumField label={t('inspector.height')} prefix="H" value={stage.h} unit="px" min={2} max={8192} disabled={!canvas} onCommit={(h) => setSize(stage.w, h)} />
</Row>
- <p className="text-[10.5px] leading-[15px] text-[var(--text-faint)]">{t(placed ? 'inspector.stageFixed' : 'viewer.canvasNote')}</p>
{/* with clips: the words that ask the agent to lay the film out again for this canvas */}
{placed ? <RedesignHint t={t} stage={stage} /> : null}
</Section>
diff --git a/packages/openfilm/studio/ui/src/components/FramePicker.tsx b/packages/openfilm/studio/ui/src/components/FramePicker.tsx
index d238812..ffd8c13 100644
--- a/packages/openfilm/studio/ui/src/components/FramePicker.tsx
+++ b/packages/openfilm/studio/ui/src/components/FramePicker.tsx
@@ -1,9 +1,8 @@
/**
* The aspect ratio button beside the picture: the film's canvas (its stage in film.html). Picking a shape changes the
- * canvas itself (`onCanvas`), as an image editor's canvas size: it grows around the film, which stays as it is,
- * centered, until the agent lays it out again. A delivery frame (bars or a crop around the film) is the export's.
- *
- * Each item draws its shape rather than only a ratio: a row of small boxes tells landscape from portrait at a glance.
+ * canvas itself (`onCanvas`), as CapCut's does: the film is scaled whole into it, centered, until the agent lays it
+ * out again. A delivery frame (bars or a crop around the film) is the export's. Any other size is typed in the
+ * inspector.
*/
import * as React from 'react';
import { Check, Proportions } from 'lucide-react';
@@ -11,27 +10,24 @@ import { useT } from '@/i18n';
import { customFilmFrame, filmFrameRatio, type FilmFrameId } from '@/lib/film-frame';
import { Tooltip } from './Tooltip';
-/**
- * The shapes a canvas is offered in, as CapCut lists them: landscape, then portrait (`hint`: a word after the ratio,
- * from viewer.ratioHint).
- */
-export const CANVAS_RATIOS: { group: 'wide' | 'tall'; id: FilmFrameId; hint?: string }[] = [
- { group: 'wide', id: '16:9', hint: 'wide' },
+/** The shapes a canvas is offered in, as CapCut lists them (and 21:9): landscape, then portrait. */
+export const CANVAS_RATIOS: { group: 'wide' | 'tall'; id: FilmFrameId; phone?: true }[] = [
+ { group: 'wide', id: '16:9' },
+ { group: 'wide', id: '21:9' },
{ group: 'wide', id: '4:3' },
{ group: 'wide', id: '2.35:1' },
{ group: 'wide', id: '2:1' },
{ group: 'wide', id: '1.85:1' },
- { group: 'tall', id: '9:16', hint: 'tall' },
+ { group: 'tall', id: '9:16' },
{ group: 'tall', id: '3:4' },
- { group: 'tall', id: '9:19.5', hint: 'phone' },
+ { group: 'tall', id: '9:19.5', phone: true },
{ group: 'tall', id: '1:1' },
{ group: 'tall', id: '1:2' },
];
-/** A ratio's name in the menu: "9:16 (TikTok)", "5.8″ phone". */
-export function canvasRatioLabel(t: (key: string) => string, item: { id: FilmFrameId; hint?: string }): string {
- if (item.hint === 'phone') return t('viewer.ratioPhone');
- return item.hint ? `${item.id} ${t(`viewer.ratioHint.${item.hint}`)}` : item.id;
+/** A ratio's name in the menu: "9:16", or "5.8″ phone" for a phone's screen. */
+export function canvasRatioLabel(t: (key: string) => string, item: { id: FilmFrameId; phone?: true }): string {
+ return item.phone ? t('viewer.ratioPhone') : item.id;
}
/** Whether the stage has this ratio (to a hundredth). */
@@ -41,7 +37,7 @@ export function FramePicker({
stage, original, busy, onCanvas,
}: {
stage: { w: number; h: number };
- /** The first picture's own size: "Fit (original)" takes its shape. None: nothing to fit to yet. */
+ /** The first picture's own size: "Original" takes its shape. None: nothing to fit to yet. */
original?: { w: number; h: number } | null;
/** The canvas change is being written: no second one meanwhile (two requests would race for one file). */
busy?: boolean;
@@ -50,14 +46,13 @@ export function FramePicker({
}): React.ReactElement {
const t = useT();
const [open, setOpen] = React.useState(false);
- const [custom, setCustom] = React.useState(false);
const box = React.useRef<HTMLDivElement | null>(null);
const fit = original ? customFilmFrame(original.w, original.h) : null;
const preset = CANVAS_RATIOS.find((r) => shaped(stage, filmFrameRatio(r.id, stage)));
const isFit = Boolean(original && shaped(stage, original.w / original.h));
React.useEffect(() => {
- if (!open) { setCustom(false); return undefined; }
+ if (!open) return undefined;
const away = (e: MouseEvent): void => {
if (!box.current?.contains(e.target as Node)) setOpen(false);
};
@@ -72,7 +67,6 @@ export function FramePicker({
<button key={r.id} type="button" disabled={busy} onClick={() => pick(r.id)} onMouseDown={(e) => e.preventDefault()} className={row}>
{tick(!isFit && preset?.id === r.id)}
<span className="flex-1">{canvasRatioLabel(t, r)}</span>
- <ShapeChip ratio={filmFrameRatio(r.id, stage)} />
</button>
);
@@ -96,17 +90,11 @@ export function FramePicker({
</button>
</Tooltip>
{open ? (
- <div className="absolute bottom-[28px] right-0 z-50 max-h-[min(520px,75vh)] w-[220px] overflow-y-auto rounded-[8px] border border-[var(--border)] bg-[var(--surface)] p-1 shadow-[var(--shadow-lg)]">
+ <div className="absolute bottom-[28px] right-0 z-50 max-h-[min(520px,75vh)] w-[180px] overflow-y-auto rounded-[8px] border border-[var(--border)] bg-[var(--surface)] p-1 shadow-[var(--shadow-lg)]">
<button type="button" disabled={busy || !fit} onClick={() => fit && pick(fit)} onMouseDown={(e) => e.preventDefault()} className={row}>
{tick(isFit)}
<span className="flex-1">{t('viewer.ratioOriginal')}</span>
</button>
- <button type="button" disabled={busy} onClick={() => setCustom((v) => !v)} onMouseDown={(e) => e.preventDefault()} className={row}>
- {tick(!isFit && !preset)}
- <span className="flex-1">{t('viewer.frameCustom')}</span>
- {!preset ? <span className="text-[11px] tabular-nums text-[var(--text-faint)]">{`${stage.w}×${stage.h}`}</span> : null}
- </button>
- {custom ? <CustomFrame value={preset?.id ?? 'native'} disabled={busy} onPick={pick} /> : null}
<div className="mx-1 my-1 h-px bg-[var(--border)]" />
{CANVAS_RATIOS.filter((r) => r.group === 'wide').map(item)}
<div className="mx-1 my-1 h-px bg-[var(--border)]" />
@@ -150,17 +138,3 @@ export function CustomFrame({ value, disabled, onPick, className = '' }: {
</div>
);
}
-
-/** A small box drawn to the ratio: the long side 16px, the short side follows. */
-function ShapeChip({ ratio }: { ratio: number }) {
- const w = ratio >= 1 ? 16 : 16 * ratio;
- const h = ratio >= 1 ? 16 / ratio : 16;
- return (
- <span className="flex h-4 w-4 shrink-0 items-center justify-center">
- <span
- className="rounded-[2px] border-[1.5px] border-current opacity-60"
- style={{ width: Math.max(4, w), height: Math.max(4, h) }}
- />
- </span>
- );
-}
diff --git a/packages/openfilm/studio/ui/src/components/ProjectView.tsx b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
index 63a5c06..7c1be58 100644
--- a/packages/openfilm/studio/ui/src/components/ProjectView.tsx
+++ b/packages/openfilm/studio/ui/src/components/ProjectView.tsx
@@ -551,12 +551,12 @@ export function ProjectView({ projectId, onProject, onLeave }: {
const [assetsPaneOpen, setAssetsPaneOpen] = useKeptFlag('openfilm.project.assets');
const [assetsWidth, setAssetsWidth] = React.useState(280);
/* the Layers panel (components/LayersPanel), left of the picture, after the assets */
- const [layersPaneOpen, setLayersPaneOpen] = useKeptFlag('openfilm.project.layers');
+ const [layersPaneOpen, setLayersPaneOpen] = useKeptFlag('openfilm.project.layers', false);
const [layersWidth, setLayersWidth] = React.useState(240);
const layersPaneRef = React.useRef<HTMLDivElement | null>(null);
const [timelineOpen, setTimelineOpen] = useKeptFlag('openfilm.project.timeline');
/* closed until it has something to show (a selection opens it), or the person opens it */
- const [inspectorOpen, persistInspector, setInspectorOpen] = useKeptFlag('openfilm.project.inspector', false);
+ const [inspectorOpen, persistInspector, setInspectorOpen] = useKeptFlag('openfilm.project.inspector', true);
const closeInspector = React.useCallback(() => persistInspector(false), [persistInspector]);
const [rowWidth, setRowWidth] = React.useState(0);
const [colHeight, setColHeight] = React.useState(0);
diff --git a/packages/openfilm/studio/ui/src/i18n/en.ts b/packages/openfilm/studio/ui/src/i18n/en.ts
index 8056e0a..7293ac6 100644
--- a/packages/openfilm/studio/ui/src/i18n/en.ts
+++ b/packages/openfilm/studio/ui/src/i18n/en.ts
@@ -744,15 +744,13 @@ export const en = {
play: 'Play',
pause: 'Pause',
frameCustom: 'Custom',
- ratioOriginal: 'Fit (original)',
+ ratioOriginal: 'Original',
ratioPhone: '5.8″ phone',
- ratioHint: { wide: '(YouTube)', tall: '(TikTok)' },
frameCustomW: 'Width',
frameCustomH: 'Height',
frameCustomApply: 'Use this ratio',
frameCustomRange: 'From 1:4 to 4:1',
canvas: 'Aspect ratio',
- canvasNote: 'The film’s canvas. Another shape keeps its short side, and the film is scaled into it whole, centered.',
fullscreen: 'Full screen',
},
inspector: {
@@ -979,7 +977,6 @@ export const en = {
film: 'Film',
stage: 'Stage',
stageShape: 'Stage shape',
- stageFixed: 'Another shape keeps the canvas’s short side, and the film is scaled into it whole, centered. Then ask your agent to lay it out again for the new canvas.',
redesignOpen: 'Ask your agent to lay it out for this canvas',
redesignBody: 'Paste these words in the chat: your agent lays out every page and clip again for the canvas as it is now.',
redesignAsk: 'This film’s canvas is now {ratio} ({size}). Lay out every page and clip again for it, and check each scene with look.',
diff --git a/packages/openfilm/studio/ui/src/i18n/es.ts b/packages/openfilm/studio/ui/src/i18n/es.ts
index 78b495f..3d7980e 100644
--- a/packages/openfilm/studio/ui/src/i18n/es.ts
+++ b/packages/openfilm/studio/ui/src/i18n/es.ts
@@ -743,15 +743,13 @@ export const es: Words = {
play: 'Reproducir',
pause: 'Pausa',
frameCustom: 'Personalizado',
- ratioOriginal: 'Ajustar (original)',
+ ratioOriginal: 'Original',
ratioPhone: 'Móvil 5,8″',
- ratioHint: { wide: '(YouTube)', tall: '(TikTok)' },
frameCustomW: 'Ancho',
frameCustomH: 'Alto',
frameCustomApply: 'Usar esta proporción',
frameCustomRange: 'De 1:4 a 4:1',
canvas: 'Relación de aspecto',
- canvasNote: 'El lienzo de la película. Otra forma mantiene su lado corto y la película se escala entera dentro, centrada.',
fullscreen: 'Pantalla completa',
},
inspector: {
@@ -978,7 +976,6 @@ export const es: Words = {
film: 'Película',
stage: 'Escenario',
stageShape: 'Forma del escenario',
- stageFixed: 'Otra forma mantiene el lado corto del lienzo y la película se escala entera dentro, centrada. Después pide a tu agente que la recomponga para el nuevo lienzo.',
redesignOpen: 'Pedir al agente que la componga para este lienzo',
redesignBody: 'Pega estas palabras en el chat: tu agente vuelve a componer cada página y clip para el lienzo actual.',
redesignAsk: 'El lienzo de esta película ahora es {ratio} ({size}). Vuelve a componer cada página y clip para él y revisa cada escena con look.',
diff --git a/packages/openfilm/studio/ui/src/i18n/ja.ts b/packages/openfilm/studio/ui/src/i18n/ja.ts
index 849d6b7..ae5ba6e 100644
--- a/packages/openfilm/studio/ui/src/i18n/ja.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ja.ts
@@ -743,15 +743,13 @@ export const ja: Words = {
play: '再生',
pause: '一時停止',
frameCustom: 'カスタム',
- ratioOriginal: 'フィット(オリジナル)',
+ ratioOriginal: 'オリジナル',
ratioPhone: '5.8 インチ',
- ratioHint: { wide: '(YouTube)', tall: '(TikTok)' },
frameCustomW: '幅',
frameCustomH: '高さ',
frameCustomApply: 'この比率を使う',
frameCustomRange: '1:4 から 4:1 まで',
canvas: 'アスペクト比',
- canvasNote: '映像のキャンバスです。比率を変えると短辺はそのままで、元の映像が全体が収まるよう縮小され中央に置かれます。',
fullscreen: '全画面表示',
},
inspector: {
@@ -978,7 +976,6 @@ export const ja: Words = {
film: 'フィルム',
stage: 'ステージ',
stageShape: 'ステージの比率',
- stageFixed: '比率を変えると短辺はそのままで、元の映像が全体が収まるよう縮小され中央に置かれます。そのあとエージェントに新しいキャンバスで組み直してもらえます。',
redesignOpen: 'このキャンバスで組み直してもらう',
redesignBody: 'この文をチャットに貼り付けると、エージェントが今のキャンバスに合わせてすべてのページとクリップを組み直します。',
redesignAsk: 'この映像のキャンバスは {ratio}({size})になりました。これに合わせてすべてのページとクリップを組み直し、look で各シーンを確認してください。',
diff --git a/packages/openfilm/studio/ui/src/i18n/ko.ts b/packages/openfilm/studio/ui/src/i18n/ko.ts
index be82c99..75e10a3 100644
--- a/packages/openfilm/studio/ui/src/i18n/ko.ts
+++ b/packages/openfilm/studio/ui/src/i18n/ko.ts
@@ -743,15 +743,13 @@ export const ko: Words = {
play: '재생',
pause: '일시 정지',
frameCustom: '사용자 지정',
- ratioOriginal: '맞춤(원본)',
+ ratioOriginal: '원본',
ratioPhone: '5.8인치',
- ratioHint: { wide: '(YouTube)', tall: '(TikTok)' },
frameCustomW: '너비',
frameCustomH: '높이',
frameCustomApply: '이 비율 사용',
frameCustomRange: '1:4부터 4:1까지',
canvas: '화면 비율',
- canvasNote: '영상의 캔버스입니다. 비율을 바꾸면 짧은 변은 그대로이고, 원래 화면이 전체가 들어가도록 비율대로 줄어 가운데에 놓입니다.',
fullscreen: '전체 화면',
},
inspector: {
@@ -978,7 +976,6 @@ export const ko: Words = {
film: '필름',
stage: '스테이지',
stageShape: '스테이지 비율',
- stageFixed: '비율을 바꾸면 짧은 변은 그대로이고, 원래 화면이 전체가 들어가도록 비율대로 줄어 가운데에 놓입니다. 그다음 에이전트에게 새 캔버스에 맞게 다시 배치해 달라고 하세요.',
redesignOpen: '이 캔버스에 맞게 다시 배치해 달라고 하기',
redesignBody: '이 문장을 채팅에 붙여 넣으면 에이전트가 지금 캔버스에 맞게 모든 페이지와 클립을 다시 배치합니다.',
redesignAsk: '이 영상의 캔버스가 이제 {ratio}({size})입니다. 여기에 맞게 모든 페이지와 클립을 다시 배치하고 look으로 각 장면을 확인해 줘.',
diff --git a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
index 5761dc4..942b3c0 100644
--- a/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
+++ b/packages/openfilm/studio/ui/src/i18n/zh-CN.ts
@@ -744,15 +744,13 @@ export const zhCN: Words = {
play: '播放',
pause: '暂停',
frameCustom: '自定义',
- ratioOriginal: '适应(原始)',
+ ratioOriginal: '原始',
ratioPhone: '5.8 寸',
- ratioHint: { wide: '(YouTube)', tall: '(抖音)' },
frameCustomW: '宽',
frameCustomH: '高',
frameCustomApply: '使用这个比例',
frameCustomRange: '范围 1:4 到 4:1',
canvas: '画面比例',
- canvasNote: '影片的画布。换比例时画布短边不变,原画面等比缩放、完整放进新画布并居中。',
fullscreen: '全屏',
},
inspector: {
@@ -979,7 +977,6 @@ export const zhCN: Words = {
film: '影片',
stage: '画布',
stageShape: '画布比例',
- stageFixed: '换比例时画布短边不变,原画面等比缩放、完整放进新画布并居中。之后可以让智能体按新画布重新排版。',
redesignOpen: '让智能体按这个画布重新排版',
redesignBody: '把下面这句话粘贴到对话里,智能体会按当前画布重新排版每个页面和片段。',
redesignAsk: '这部影片的画布现在是 {ratio}({size})。请按这个画布重新排版每个页面和片段,并用 look 检查每一幕。',
diff --git a/packages/openfilm/studio/ui/src/lib/canvas-fit.test.ts b/packages/openfilm/studio/ui/src/lib/canvas-fit.test.ts
index 03dcf3f..adbc578 100644
--- a/packages/openfilm/studio/ui/src/lib/canvas-fit.test.ts
+++ b/packages/openfilm/studio/ui/src/lib/canvas-fit.test.ts
@@ -33,3 +33,23 @@ test('a page laid out at the canvas keeps the old canvas as its size, so it is s
assert.equal(out.find((c) => c.id === 'sized')?.size, undefined);
assert.equal(out.find((c) => c.id === 'given')?.size, undefined);
});
+
+test('shapes picked one after another never shrink the film: what it shows is fitted to each canvas, an edge met', () => {
+ const clip = (box?: { x: number; y: number; w: number; h: number }) => [{ id: 'v', kind: 'video' as const, own: { w: 1920, h: 1080 }, box }];
+ const wide = { w: 1920, h: 1080 }, tall = { w: 1080, h: 1440 }, cinema = { w: 2538, h: 1080 };
+ const first = fitToCanvas(clip(), wide, tall)[0].box;
+ assert.deepEqual(first, { x: 0, y: 416, w: 1080, h: 608 });
+ /* 3:4 → 2.35:1: the 16:9 picture fills the height, centered (not 3:4's small picture made smaller) */
+ const second = fitToCanvas(clip(first as never), tall, cinema)[0].box;
+ assert.deepEqual(second, { x: 310, y: 0, w: 1918, h: 1080 });
+ /* back to 16:9: the whole frame again */
+ const third = fitToCanvas(clip(second as never), cinema, wide)[0].box;
+ assert.deepEqual(third, { x: 0, y: 0, w: 1920, h: 1080 });
+});
+
+test('a film already shrunk in its canvas is fitted out to the edge on the next shape; a title alone fills it too', () => {
+ const small = fitToCanvas([{ id: 'v', kind: 'video', own: { w: 1920, h: 1080 }, box: { x: 1000, y: 400, w: 540, h: 304 } }], { w: 2538, h: 1080 }, { w: 1920, h: 1080 });
+ assert.deepEqual(small[0].box, { x: 0, y: 0, w: 1920, h: 1080 });
+ const title = fitToCanvas([{ id: 't', kind: 'still', own: { w: 400, h: 200 }, box: { x: 760, y: 440, w: 400, h: 200 } }], { w: 1920, h: 1080 }, { w: 1080, h: 1440 });
+ assert.deepEqual(title[0].box, { x: 0, y: 450, w: 1080, h: 540 });
+});
diff --git a/packages/openfilm/studio/ui/src/lib/canvas-fit.ts b/packages/openfilm/studio/ui/src/lib/canvas-fit.ts
index e22a5b6..370aca8 100644
--- a/packages/openfilm/studio/ui/src/lib/canvas-fit.ts
+++ b/packages/openfilm/studio/ui/src/lib/canvas-fit.ts
@@ -1,11 +1,12 @@
/**
* A film's canvas changing shape, as an editor's (CapCut's) does: the canvas takes the new shape with its short side
- * kept (a 1920×1080 film made 3:4 is 1080×1440), and every picture on it is scaled by one factor, the largest that
- * keeps the old canvas whole inside the new one, about the middle: the film shows as it was, smaller or larger,
- * centered, with room around it. Nothing is cut. What a picture is drawn as (film-doc's pictureRect) is written as its
- * box, so a video that filled the old canvas (no box of its own) keeps that place rather than filling the new one.
- * A page that sets no size of its own is laid out at the canvas's: it is given the old canvas as its `size`, so it is
- * scaled as a video is rather than laid out again in the new shape.
+ * kept (a 1920×1080 film made 3:4 is 1080×1440), and what the film shows is scaled whole into it, centered, as large
+ * as fits: the part of the old canvas its pictures cover is fitted to the new canvas, so at least one side of it meets
+ * the canvas's edge. It is worked out from where the pictures are, not from the old canvas, so shapes picked one after
+ * another never shrink the film further. Nothing is cut. What a picture is drawn as (film-doc's pictureRect) is
+ * written as its box, so a video that filled the old canvas (no box of its own) keeps that place rather than filling
+ * the new one. A page that sets no size of its own is laid out at the canvas's: it is given the old canvas as its
+ * `size`, so it is scaled as a video is rather than laid out again in the new shape.
*/
import { pictureRect } from '../../../../src/film-doc.mjs';
import { frameRatioOf, type FilmFrameId } from './film-frame.ts';
@@ -33,23 +34,47 @@ export interface CanvasClip { id: string; kind: FilmSrcKind | null; own?: Size |
/** A clip on the new canvas: its box, and for a page laid out at the old canvas, that size. */
export interface CanvasFit { id: string; box: FilmBox; size?: Size }
+type Rect = { x: number; y: number; w: number; h: number; r: number };
+
+/** The upright rectangle around a picture as drawn (turned about its center by `r` degrees). */
+function bounds(at: Rect) {
+ const t = (at.r * Math.PI) / 180;
+ const w = Math.abs(at.w * Math.cos(t)) + Math.abs(at.h * Math.sin(t));
+ const h = Math.abs(at.w * Math.sin(t)) + Math.abs(at.h * Math.cos(t));
+ const cx = at.x + at.w / 2, cy = at.y + at.h / 2;
+ return { x0: cx - w / 2, y0: cy - h / 2, x1: cx + w / 2, y1: cy + h / 2 };
+}
+
/**
- * Each picture clip's box on the new canvas `to` (the old one is `from`): scaled by min(to.w / from.w, to.h / from.h)
- * about the middle of each canvas. Sounds have no picture and are left out.
+ * Each picture clip's box on the new canvas `to` (the old one is `from`): what the pictures cover of the old canvas
+ * (the canvas itself when they cover none of it) is scaled to fit `to` whole and centered in it. Sounds have no
+ * picture and are left out.
*/
export function fitToCanvas(clips: readonly CanvasClip[], from: Size, to: Size): CanvasFit[] {
- const k = Math.min(to.w / from.w, to.h / from.h);
- const out: CanvasFit[] = [];
- for (const clip of clips) {
- if (!clip.kind || clip.kind === 'sound') continue;
+ const drawn = clips.flatMap((clip) => {
+ if (!clip.kind || clip.kind === 'sound') return [];
const own = clip.own && clip.own.w > 0 && clip.own.h > 0 ? clip.own : from;
- const at = pictureRect(clip.kind, own, from, clip.box ?? undefined);
+ return [{ clip, at: pictureRect(clip.kind, own, from, clip.box ?? undefined) as Rect }];
+ });
+ /* what the film shows: its pictures' extent, as far as the old canvas shows it */
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
+ for (const { at } of drawn) {
+ const b = bounds(at);
+ x0 = Math.min(x0, b.x0); y0 = Math.min(y0, b.y0); x1 = Math.max(x1, b.x1); y1 = Math.max(y1, b.y1);
+ }
+ x0 = Math.max(0, x0); y0 = Math.max(0, y0); x1 = Math.min(from.w, x1); y1 = Math.min(from.h, y1);
+ if (!(x1 - x0 >= 1 && y1 - y0 >= 1)) { x0 = 0; y0 = 0; x1 = from.w; y1 = from.h; }
+ const k = Math.min(to.w / (x1 - x0), to.h / (y1 - y0));
+ const mx = (x0 + x1) / 2, my = (y0 + y1) / 2;
+ return drawn.map(({ clip, at }) => {
const w = at.w * k, h = at.h * k;
- const cx = (at.x + at.w / 2 - from.w / 2) * k + to.w / 2;
- const cy = (at.y + at.h / 2 - from.h / 2) * k + to.h / 2;
- const box: FilmBox = { x: Math.round(cx - w / 2), y: Math.round(cy - h / 2), w: Math.round(w), h: Math.round(h) };
+ const cx = (at.x + at.w / 2 - mx) * k + to.w / 2;
+ const cy = (at.y + at.h / 2 - my) * k + to.h / 2;
+ /* whole px; an edge within 2 px of the canvas's meets it, so rounding never leaves a hairline of black */
+ const near = (v: number, edge: number) => (Math.abs(v - edge) <= 2 ? edge : Math.round(v));
+ const left = near(cx - w / 2, 0), top = near(cy - h / 2, 0);
+ const box: FilmBox = { x: left, y: top, w: near(cx + w / 2, to.w) - left, h: near(cy + h / 2, to.h) - top };
if (at.r) box.r = at.r;
- out.push(clip.kind === 'page' && clip.reflows && !clip.size ? { id: clip.id, box, size: { w: from.w, h: from.h } } : { id: clip.id, box });
- }
- return out;
+ return clip.kind === 'page' && clip.reflows && !clip.size ? { id: clip.id, box, size: { w: from.w, h: from.h } } : { id: clip.id, box };
+ });
}