feat: improve library preview image generation on publish (#4321)

Co-authored-by: Aakansha Doshi <aakansha1216@gmail.com>
This commit is contained in:
David Luzar 2021-11-26 11:46:13 +01:00 committed by GitHub
parent ca1f3aa094
commit b53d1f6f3e
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 157 additions and 72 deletions

View file

@ -13,17 +13,19 @@ type ExportOpts = {
elements: readonly NonDeleted<ExcalidrawElement>[];
appState?: Partial<Omit<AppState, "offsetTop" | "offsetLeft">>;
files: BinaryFiles | null;
maxWidthOrHeight?: number;
getDimensions?: (
width: number,
height: number,
) => { width: number; height: number; scale: number };
) => { width: number; height: number; scale?: number };
};
export const exportToCanvas = ({
elements,
appState,
files,
getDimensions = (width, height) => ({ width, height, scale: 1 }),
maxWidthOrHeight,
getDimensions,
}: ExportOpts) => {
const { elements: restoredElements, appState: restoredAppState } = restore(
{ elements, appState },
@ -38,12 +40,36 @@ export const exportToCanvas = ({
{ exportBackground, viewBackgroundColor },
(width: number, height: number) => {
const canvas = document.createElement("canvas");
const ret = getDimensions(width, height);
if (maxWidthOrHeight) {
if (typeof getDimensions === "function") {
console.warn(
"`getDimensions()` is ignored when `maxWidthOrHeight` is supplied.",
);
}
const max = Math.max(width, height);
const scale = maxWidthOrHeight / max;
canvas.width = width * scale;
canvas.height = height * scale;
return {
canvas,
scale,
};
}
const ret = getDimensions?.(width, height) || { width, height };
canvas.width = ret.width;
canvas.height = ret.height;
return { canvas, scale: ret.scale };
return {
canvas,
scale: ret.scale ?? 1,
};
},
);
};