Compare commits
6 Commits
master
...
dwelle/fix
Author | SHA1 | Date | |
---|---|---|---|
|
16a2431fd8 | ||
|
b71bf2072e | ||
|
f1923acf05 | ||
|
d81e0afa19 | ||
|
41de1fa951 | ||
|
33ab88926f |
@ -8,7 +8,7 @@ import {
|
||||
} from "../clipboard";
|
||||
import { actionDeleteSelected } from "./actionDeleteSelected";
|
||||
import { getSelectedElements } from "../scene/selection";
|
||||
import { exportCanvas } from "../data/index";
|
||||
import { exportAsImage } from "../data/index";
|
||||
import { getNonDeletedElements, isTextElement } from "../element";
|
||||
import { t } from "../i18n";
|
||||
|
||||
@ -78,7 +78,7 @@ export const actionCopyAsSvg = register({
|
||||
true,
|
||||
);
|
||||
try {
|
||||
await exportCanvas(
|
||||
await exportAsImage(
|
||||
"clipboard-svg",
|
||||
selectedElements.length
|
||||
? selectedElements
|
||||
@ -122,7 +122,7 @@ export const actionCopyAsPng = register({
|
||||
true,
|
||||
);
|
||||
try {
|
||||
await exportCanvas(
|
||||
await exportAsImage(
|
||||
"clipboard",
|
||||
selectedElements.length
|
||||
? selectedElements
|
||||
|
@ -10,13 +10,13 @@ import { useDevice } from "../components/App";
|
||||
import { KEYS } from "../keys";
|
||||
import { register } from "./register";
|
||||
import { CheckboxItem } from "../components/CheckboxItem";
|
||||
import { getExportSize } from "../scene/export";
|
||||
import { getCanvasSize } from "../scene/export";
|
||||
import { DEFAULT_EXPORT_PADDING, EXPORT_SCALES, THEME } from "../constants";
|
||||
import { getSelectedElements, isSomeElementSelected } from "../scene";
|
||||
import { getNonDeletedElements } from "../element";
|
||||
import { isImageFileHandle } from "../data/blob";
|
||||
import { nativeFileSystemSupported } from "../data/filesystem";
|
||||
import { Theme } from "../element/types";
|
||||
import { NonDeletedExcalidrawElement, Theme } from "../element/types";
|
||||
|
||||
import "../components/ToolIcon.scss";
|
||||
|
||||
@ -54,6 +54,18 @@ export const actionChangeExportScale = register({
|
||||
? getSelectedElements(elements, appState)
|
||||
: elements;
|
||||
|
||||
const getExportSize = (
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
padding: number,
|
||||
scale: number,
|
||||
): [number, number] => {
|
||||
const [, , width, height] = getCanvasSize(elements).map((dimension) =>
|
||||
Math.trunc(dimension * scale),
|
||||
);
|
||||
|
||||
return [width + padding * 2, height + padding * 2];
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{EXPORT_SCALES.map((s) => {
|
||||
|
@ -1,14 +1,15 @@
|
||||
import oc from "open-color";
|
||||
import {
|
||||
DEFAULT_BACKGROUND_COLOR,
|
||||
DEFAULT_ELEMENT_PROPS,
|
||||
DEFAULT_FONT_FAMILY,
|
||||
DEFAULT_FONT_SIZE,
|
||||
DEFAULT_TEXT_ALIGN,
|
||||
DEFAULT_ZOOM_VALUE,
|
||||
EXPORT_SCALES,
|
||||
THEME,
|
||||
} from "./constants";
|
||||
import { t } from "./i18n";
|
||||
import { AppState, NormalizedZoomValue } from "./types";
|
||||
import { AppState } from "./types";
|
||||
import { getDateTime } from "./utils";
|
||||
|
||||
const defaultExportScale = EXPORT_SCALES.includes(devicePixelRatio)
|
||||
@ -84,10 +85,10 @@ export const getDefaultAppState = (): Omit<
|
||||
startBoundElement: null,
|
||||
suggestedBindings: [],
|
||||
toast: null,
|
||||
viewBackgroundColor: oc.white,
|
||||
viewBackgroundColor: DEFAULT_BACKGROUND_COLOR,
|
||||
zenModeEnabled: false,
|
||||
zoom: {
|
||||
value: 1 as NormalizedZoomValue,
|
||||
value: DEFAULT_ZOOM_VALUE,
|
||||
},
|
||||
viewModeEnabled: false,
|
||||
pendingImageElementId: null,
|
||||
|
@ -1375,14 +1375,14 @@ class App extends React.Component<AppProps, AppState> {
|
||||
{
|
||||
elements: renderingElements,
|
||||
appState: this.state,
|
||||
scale: window.devicePixelRatio,
|
||||
rc: this.rc!,
|
||||
canvas: this.canvas!,
|
||||
renderConfig: {
|
||||
canvasScale: window.devicePixelRatio,
|
||||
selectionColor,
|
||||
scrollX: this.state.scrollX,
|
||||
scrollY: this.state.scrollY,
|
||||
viewBackgroundColor: this.state.viewBackgroundColor,
|
||||
canvasBackgroundColor: this.state.viewBackgroundColor,
|
||||
zoom: this.state.zoom,
|
||||
remotePointerViewportCoords: pointerViewportCoords,
|
||||
remotePointerButton: cursorButton,
|
||||
|
@ -103,11 +103,20 @@ const ImageExportModal = ({
|
||||
return;
|
||||
}
|
||||
exportToCanvas({
|
||||
data: {
|
||||
elements: exportedElements,
|
||||
appState,
|
||||
files,
|
||||
exportPadding,
|
||||
},
|
||||
config: {
|
||||
canvasBackgroundColor: !appState.exportBackground
|
||||
? false
|
||||
: appState.viewBackgroundColor,
|
||||
padding: exportPadding,
|
||||
theme: appState.exportWithDarkMode ? "dark" : "light",
|
||||
scale: appState.exportScale,
|
||||
maxWidthOrHeight: maxWidth,
|
||||
},
|
||||
})
|
||||
.then((canvas) => {
|
||||
setRenderError(null);
|
||||
|
@ -2,7 +2,7 @@ import clsx from "clsx";
|
||||
import React from "react";
|
||||
import { ActionManager } from "../actions/manager";
|
||||
import { CLASSES, DEFAULT_SIDEBAR, LIBRARY_SIDEBAR_WIDTH } from "../constants";
|
||||
import { exportCanvas } from "../data";
|
||||
import { exportAsImage } from "../data";
|
||||
import { isTextElement, showSelectedShapeActions } from "../element";
|
||||
import { NonDeletedExcalidrawElement } from "../element/types";
|
||||
import { Language, t } from "../i18n";
|
||||
@ -141,7 +141,7 @@ const LayerUI = ({
|
||||
(type: ExportType): ExportCB =>
|
||||
async (exportedElements) => {
|
||||
trackEvent("export", type, "ui");
|
||||
const fileHandle = await exportCanvas(
|
||||
const fileHandle = await exportAsImage(
|
||||
type,
|
||||
exportedElements,
|
||||
appState,
|
||||
|
@ -37,12 +37,14 @@ export const LibraryUnit = ({
|
||||
return;
|
||||
}
|
||||
const svg = await exportToSvg({
|
||||
data: {
|
||||
elements,
|
||||
appState: {
|
||||
exportBackground: false,
|
||||
viewBackgroundColor: oc.white,
|
||||
},
|
||||
files: null,
|
||||
},
|
||||
});
|
||||
svg.querySelector(".style-fonts")?.remove();
|
||||
node.innerHTML = svg.outerHTML;
|
||||
|
@ -86,9 +86,13 @@ const generatePreviewImage = async (libraryItems: LibraryItems) => {
|
||||
// ---------------------------------------------------------------------------
|
||||
for (const [index, item] of libraryItems.entries()) {
|
||||
const itemCanvas = await exportToCanvas({
|
||||
data: {
|
||||
elements: item.elements,
|
||||
files: null,
|
||||
},
|
||||
config: {
|
||||
maxWidthOrHeight: BOX_SIZE,
|
||||
},
|
||||
});
|
||||
|
||||
const { width, height } = itemCanvas;
|
||||
@ -150,6 +154,7 @@ const SingleLibraryItem = ({
|
||||
}
|
||||
(async () => {
|
||||
const svg = await exportToSvg({
|
||||
data: {
|
||||
elements: libItem.elements,
|
||||
appState: {
|
||||
...appState,
|
||||
@ -157,6 +162,7 @@ const SingleLibraryItem = ({
|
||||
exportBackground: true,
|
||||
},
|
||||
files: null,
|
||||
},
|
||||
});
|
||||
node.innerHTML = svg.outerHTML;
|
||||
})();
|
||||
|
@ -1,5 +1,5 @@
|
||||
import cssVariables from "./css/variables.module.scss";
|
||||
import { AppProps } from "./types";
|
||||
import { AppProps, NormalizedZoomValue } from "./types";
|
||||
import { ExcalidrawElement, FontFamilyValues } from "./element/types";
|
||||
import oc from "open-color";
|
||||
|
||||
@ -75,6 +75,7 @@ export enum EVENT {
|
||||
export const ENV = {
|
||||
TEST: "test",
|
||||
DEVELOPMENT: "development",
|
||||
PRODUCTION: "production",
|
||||
};
|
||||
|
||||
export const CLASSES = {
|
||||
@ -100,6 +101,9 @@ export const DEFAULT_FONT_FAMILY: FontFamilyValues = FONT_FAMILY.Virgil;
|
||||
export const DEFAULT_TEXT_ALIGN = "left";
|
||||
export const DEFAULT_VERTICAL_ALIGN = "top";
|
||||
export const DEFAULT_VERSION = "{version}";
|
||||
export const DEFAULT_BACKGROUND_COLOR = "#ffffff";
|
||||
export const DEFAULT_STROKE_COLOR = "#000000";
|
||||
export const DEFAULT_ZOOM_VALUE = 1 as NormalizedZoomValue;
|
||||
|
||||
export const CANVAS_ONLY_ACTIONS = ["selectAll"];
|
||||
|
||||
|
@ -15,7 +15,7 @@ import { serializeAsJSON } from "./json";
|
||||
export { loadFromBlob } from "./blob";
|
||||
export { loadFromJSON, saveAsJSON } from "./json";
|
||||
|
||||
export const exportCanvas = async (
|
||||
export const exportAsImage = async (
|
||||
type: Omit<ExportType, "backend">,
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
appState: AppState,
|
||||
@ -66,10 +66,19 @@ export const exportCanvas = async (
|
||||
}
|
||||
}
|
||||
|
||||
const tempCanvas = await exportToCanvas(elements, appState, files, {
|
||||
exportBackground,
|
||||
viewBackgroundColor,
|
||||
exportPadding,
|
||||
const tempCanvas = await exportToCanvas({
|
||||
data: {
|
||||
elements,
|
||||
appState,
|
||||
files,
|
||||
},
|
||||
config: {
|
||||
canvasBackgroundColor: !exportBackground ? false : viewBackgroundColor,
|
||||
padding: exportPadding,
|
||||
theme: appState.exportWithDarkMode ? "dark" : "light",
|
||||
scale: appState.exportScale,
|
||||
fit: "none",
|
||||
},
|
||||
});
|
||||
tempCanvas.style.display = "none";
|
||||
document.body.appendChild(tempCanvas);
|
||||
|
@ -1,6 +1,6 @@
|
||||
import { ExcalidrawElement } from "../element/types";
|
||||
import { AppState, BinaryFiles } from "../types";
|
||||
import { exportCanvas } from ".";
|
||||
import { exportAsImage } from ".";
|
||||
import { getNonDeletedElements } from "../element";
|
||||
import { getFileHandleType, isImageFileHandleType } from "./blob";
|
||||
|
||||
@ -23,7 +23,7 @@ export const resaveAsImageWithScene = async (
|
||||
exportEmbedScene: true,
|
||||
};
|
||||
|
||||
await exportCanvas(
|
||||
await exportAsImage(
|
||||
fileHandleType,
|
||||
getNonDeletedElements(elements),
|
||||
appState,
|
||||
|
@ -57,22 +57,21 @@ const elements = [
|
||||
registerFont("./public/Virgil.woff2", { family: "Virgil" });
|
||||
registerFont("./public/Cascadia.woff2", { family: "Cascadia" });
|
||||
|
||||
const canvas = exportToCanvas(
|
||||
elements as any,
|
||||
{
|
||||
const canvas = exportToCanvas({
|
||||
data: {
|
||||
elements: elements as any,
|
||||
appState: {
|
||||
...getDefaultAppState(),
|
||||
offsetTop: 0,
|
||||
offsetLeft: 0,
|
||||
width: 0,
|
||||
height: 0,
|
||||
},
|
||||
{}, // files
|
||||
{
|
||||
exportBackground: true,
|
||||
viewBackgroundColor: "#ffffff",
|
||||
files: {}, // files
|
||||
},
|
||||
config: {
|
||||
canvasBackgroundColor: "#ffffff",
|
||||
createCanvas,
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
const fs = require("fs");
|
||||
const out = fs.createWriteStream("test.png");
|
||||
|
@ -252,10 +252,12 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
|
||||
return false;
|
||||
}
|
||||
await exportToClipboard({
|
||||
data: {
|
||||
elements: excalidrawAPI.getSceneElements(),
|
||||
appState: excalidrawAPI.getAppState(),
|
||||
files: excalidrawAPI.getFiles(),
|
||||
type,
|
||||
},
|
||||
type: "json",
|
||||
});
|
||||
window.alert(`Copied to clipboard as ${type} successfully`);
|
||||
};
|
||||
@ -740,6 +742,7 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
|
||||
return;
|
||||
}
|
||||
const svg = await exportToSvg({
|
||||
data: {
|
||||
elements: excalidrawAPI?.getSceneElements(),
|
||||
appState: {
|
||||
...initialData.appState,
|
||||
@ -749,6 +752,7 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
|
||||
height: 100,
|
||||
},
|
||||
files: excalidrawAPI?.getFiles(),
|
||||
},
|
||||
});
|
||||
appRef.current.querySelector(".export-svg").innerHTML =
|
||||
svg.outerHTML;
|
||||
@ -764,14 +768,18 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
|
||||
return;
|
||||
}
|
||||
const blob = await exportToBlob({
|
||||
data: {
|
||||
elements: excalidrawAPI?.getSceneElements(),
|
||||
mimeType: "image/png",
|
||||
appState: {
|
||||
...initialData.appState,
|
||||
exportEmbedScene,
|
||||
exportWithDarkMode,
|
||||
},
|
||||
files: excalidrawAPI?.getFiles(),
|
||||
},
|
||||
config: {
|
||||
mimeType: "image/png",
|
||||
},
|
||||
});
|
||||
setBlobUrl(window.URL.createObjectURL(blob));
|
||||
}}
|
||||
@ -788,12 +796,14 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
|
||||
return;
|
||||
}
|
||||
const canvas = await exportToCanvas({
|
||||
data: {
|
||||
elements: excalidrawAPI.getSceneElements(),
|
||||
appState: {
|
||||
...initialData.appState,
|
||||
exportWithDarkMode,
|
||||
},
|
||||
files: excalidrawAPI.getFiles(),
|
||||
},
|
||||
});
|
||||
const ctx = canvas.getContext("2d")!;
|
||||
ctx.font = "30px Virgil";
|
||||
|
@ -206,7 +206,6 @@ export {
|
||||
restoreLibraryItems,
|
||||
} from "../../data/restore";
|
||||
export {
|
||||
exportToCanvas,
|
||||
exportToBlob,
|
||||
exportToSvg,
|
||||
serializeAsJSON,
|
||||
@ -245,5 +244,6 @@ export { MainMenu };
|
||||
export { useDevice } from "../../components/App";
|
||||
export { WelcomeScreen };
|
||||
export { LiveCollaborationTrigger };
|
||||
|
||||
export { DefaultSidebar } from "../../components/DefaultSidebar";
|
||||
|
||||
export { exportToCanvas } from "../../scene/export";
|
||||
|
@ -1,12 +1,13 @@
|
||||
import {
|
||||
exportToCanvas as _exportToCanvas,
|
||||
ExportToCanvasConfig,
|
||||
ExportToCanvasData,
|
||||
exportToSvg as _exportToSvg,
|
||||
} from "../scene/export";
|
||||
import { getDefaultAppState } from "../appState";
|
||||
import { AppState, BinaryFiles } from "../types";
|
||||
import { ExcalidrawElement, NonDeleted } from "../element/types";
|
||||
import { getNonDeletedElements } from "../element";
|
||||
import { ExcalidrawElement } from "../element/types";
|
||||
import { restore } from "../data/restore";
|
||||
import { MIME_TYPES } from "../constants";
|
||||
import { DEFAULT_BACKGROUND_COLOR, MIME_TYPES } from "../constants";
|
||||
import { encodePngMetadata } from "../data/image";
|
||||
import { serializeAsJSON } from "../data/json";
|
||||
import {
|
||||
@ -35,86 +36,24 @@ const passElementsSafely = (elements: readonly ExcalidrawElement[]) => {
|
||||
|
||||
export { MIME_TYPES };
|
||||
|
||||
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 };
|
||||
};
|
||||
|
||||
export const exportToCanvas = ({
|
||||
elements,
|
||||
appState,
|
||||
files,
|
||||
maxWidthOrHeight,
|
||||
getDimensions,
|
||||
exportPadding,
|
||||
}: ExportOpts & {
|
||||
exportPadding?: number;
|
||||
}) => {
|
||||
const { elements: restoredElements, appState: restoredAppState } = restore(
|
||||
{ elements, appState },
|
||||
null,
|
||||
null,
|
||||
);
|
||||
const { exportBackground, viewBackgroundColor } = restoredAppState;
|
||||
return _exportToCanvas(
|
||||
passElementsSafely(restoredElements),
|
||||
{ ...restoredAppState, offsetTop: 0, offsetLeft: 0, width: 0, height: 0 },
|
||||
files || {},
|
||||
{ exportBackground, exportPadding, viewBackgroundColor },
|
||||
(width: number, height: number) => {
|
||||
const canvas = document.createElement("canvas");
|
||||
|
||||
if (maxWidthOrHeight) {
|
||||
if (typeof getDimensions === "function") {
|
||||
console.warn(
|
||||
"`getDimensions()` is ignored when `maxWidthOrHeight` is supplied.",
|
||||
);
|
||||
}
|
||||
|
||||
const max = Math.max(width, height);
|
||||
|
||||
// if content is less then maxWidthOrHeight, fallback on supplied scale
|
||||
const scale =
|
||||
maxWidthOrHeight < max
|
||||
? maxWidthOrHeight / max
|
||||
: appState?.exportScale ?? 1;
|
||||
|
||||
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 ?? 1,
|
||||
};
|
||||
},
|
||||
);
|
||||
};
|
||||
|
||||
export const exportToBlob = async (
|
||||
opts: ExportOpts & {
|
||||
type ExportToBlobConfig = ExportToCanvasConfig & {
|
||||
mimeType?: string;
|
||||
quality?: number;
|
||||
exportPadding?: number;
|
||||
},
|
||||
): Promise<Blob> => {
|
||||
let { mimeType = MIME_TYPES.png, quality } = opts;
|
||||
};
|
||||
|
||||
type ExportToSvgConfig = Pick<
|
||||
ExportToCanvasConfig,
|
||||
"canvasBackgroundColor" | "padding" | "theme"
|
||||
>;
|
||||
|
||||
export const exportToBlob = async ({
|
||||
data,
|
||||
config,
|
||||
}: {
|
||||
data: ExportToCanvasData;
|
||||
config?: ExportToBlobConfig;
|
||||
}): Promise<Blob> => {
|
||||
let { mimeType = MIME_TYPES.png, quality } = config || {};
|
||||
|
||||
if (mimeType === MIME_TYPES.png && typeof quality === "number") {
|
||||
console.warn(`"quality" will be ignored for "${MIME_TYPES.png}" mimeType`);
|
||||
@ -125,19 +64,23 @@ export const exportToBlob = async (
|
||||
mimeType = MIME_TYPES.jpg;
|
||||
}
|
||||
|
||||
if (mimeType === MIME_TYPES.jpg && !opts.appState?.exportBackground) {
|
||||
if (mimeType === MIME_TYPES.jpg && !config?.canvasBackgroundColor === false) {
|
||||
console.warn(
|
||||
`Defaulting "exportBackground" to "true" for "${MIME_TYPES.jpg}" mimeType`,
|
||||
);
|
||||
opts = {
|
||||
...opts,
|
||||
appState: { ...opts.appState, exportBackground: true },
|
||||
config = {
|
||||
...config,
|
||||
canvasBackgroundColor:
|
||||
data.appState?.viewBackgroundColor || DEFAULT_BACKGROUND_COLOR,
|
||||
};
|
||||
}
|
||||
|
||||
const canvas = await exportToCanvas({
|
||||
...opts,
|
||||
elements: passElementsSafely(opts.elements),
|
||||
const canvas = await _exportToCanvas({
|
||||
data: {
|
||||
...data,
|
||||
elements: passElementsSafely(data.elements),
|
||||
},
|
||||
config,
|
||||
});
|
||||
quality = quality ? quality : /image\/jpe?g/.test(mimeType) ? 0.92 : 0.8;
|
||||
|
||||
@ -150,7 +93,7 @@ export const exportToBlob = async (
|
||||
if (
|
||||
blob &&
|
||||
mimeType === MIME_TYPES.png &&
|
||||
opts.appState?.exportEmbedScene
|
||||
data.appState?.exportEmbedScene
|
||||
) {
|
||||
blob = await encodePngMetadata({
|
||||
blob,
|
||||
@ -158,9 +101,9 @@ export const exportToBlob = async (
|
||||
// NOTE as long as we're using the Scene hack, we need to ensure
|
||||
// we pass the original, uncloned elements when serializing
|
||||
// so that we keep ids stable
|
||||
opts.elements,
|
||||
opts.appState,
|
||||
opts.files || {},
|
||||
data.elements,
|
||||
data.appState,
|
||||
data.files || {},
|
||||
"local",
|
||||
),
|
||||
});
|
||||
@ -174,53 +117,62 @@ export const exportToBlob = async (
|
||||
};
|
||||
|
||||
export const exportToSvg = async ({
|
||||
elements,
|
||||
appState = getDefaultAppState(),
|
||||
files = {},
|
||||
exportPadding,
|
||||
}: Omit<ExportOpts, "getDimensions"> & {
|
||||
exportPadding?: number;
|
||||
data,
|
||||
config,
|
||||
}: {
|
||||
data: ExportToCanvasData;
|
||||
config?: ExportToSvgConfig;
|
||||
}): Promise<SVGSVGElement> => {
|
||||
const { elements: restoredElements, appState: restoredAppState } = restore(
|
||||
{ elements, appState },
|
||||
{ ...data, files: data.files || {} },
|
||||
null,
|
||||
null,
|
||||
);
|
||||
|
||||
const exportAppState = {
|
||||
...restoredAppState,
|
||||
exportPadding,
|
||||
};
|
||||
const appState = { ...restoredAppState, exportPadding: config?.padding };
|
||||
const elements = getNonDeletedElements(restoredElements);
|
||||
const files = data.files || {};
|
||||
|
||||
return _exportToSvg(
|
||||
passElementsSafely(restoredElements),
|
||||
exportAppState,
|
||||
files,
|
||||
{
|
||||
return _exportToSvg(passElementsSafely(elements), appState, files, {
|
||||
// NOTE as long as we're using the Scene hack, we need to ensure
|
||||
// we pass the original, uncloned elements when serializing
|
||||
// so that we keep ids stable. Hence adding the serializeAsJSON helper
|
||||
// support into the downstream exportToSvg function.
|
||||
serializeAsJSON: () =>
|
||||
serializeAsJSON(restoredElements, exportAppState, files || {}, "local"),
|
||||
},
|
||||
);
|
||||
serializeAsJSON: () => serializeAsJSON(elements, appState, files, "local"),
|
||||
});
|
||||
};
|
||||
|
||||
export const exportToClipboard = async (
|
||||
opts: ExportOpts & {
|
||||
mimeType?: string;
|
||||
quality?: number;
|
||||
type: "png" | "svg" | "json";
|
||||
},
|
||||
) => {
|
||||
if (opts.type === "svg") {
|
||||
const svg = await exportToSvg(opts);
|
||||
export const exportToCanvas = async ({
|
||||
data,
|
||||
config,
|
||||
}: {
|
||||
data: ExportToCanvasData;
|
||||
config?: ExportToCanvasConfig;
|
||||
}) => {
|
||||
return _exportToCanvas({
|
||||
data: { ...data, elements: passElementsSafely(data.elements) },
|
||||
config,
|
||||
});
|
||||
};
|
||||
|
||||
export const exportToClipboard = async ({
|
||||
type,
|
||||
data,
|
||||
config,
|
||||
}: {
|
||||
data: ExportToCanvasData;
|
||||
} & (
|
||||
| { type: "png"; config?: ExportToBlobConfig }
|
||||
| { type: "svg"; config?: ExportToSvgConfig }
|
||||
| { type: "json"; config?: never }
|
||||
)) => {
|
||||
if (type === "svg") {
|
||||
const svg = await exportToSvg({ data, config });
|
||||
await copyTextToSystemClipboard(svg.outerHTML);
|
||||
} else if (opts.type === "png") {
|
||||
await copyBlobToClipboardAsPng(exportToBlob(opts));
|
||||
} else if (opts.type === "json") {
|
||||
await copyToClipboard(opts.elements, opts.files);
|
||||
} else if (type === "png") {
|
||||
await copyBlobToClipboardAsPng(exportToBlob({ data, config }));
|
||||
} else if (type === "json") {
|
||||
await copyToClipboard(data.elements, data.files);
|
||||
} else {
|
||||
throw new Error("Invalid export type");
|
||||
}
|
||||
|
@ -317,14 +317,12 @@ const renderLinearElementPointHighlight = (
|
||||
export const _renderScene = ({
|
||||
elements,
|
||||
appState,
|
||||
scale,
|
||||
rc,
|
||||
canvas,
|
||||
renderConfig,
|
||||
}: {
|
||||
elements: readonly NonDeletedExcalidrawElement[];
|
||||
appState: AppState;
|
||||
scale: number;
|
||||
rc: RoughCanvas;
|
||||
canvas: HTMLCanvasElement;
|
||||
renderConfig: RenderConfig;
|
||||
@ -347,27 +345,27 @@ export const _renderScene = ({
|
||||
|
||||
context.setTransform(1, 0, 0, 1, 0, 0);
|
||||
context.save();
|
||||
context.scale(scale, scale);
|
||||
context.scale(renderConfig.canvasScale, renderConfig.canvasScale);
|
||||
// When doing calculations based on canvas width we should used normalized one
|
||||
const normalizedCanvasWidth = canvas.width / scale;
|
||||
const normalizedCanvasHeight = canvas.height / scale;
|
||||
const normalizedCanvasWidth = canvas.width / renderConfig.canvasScale;
|
||||
const normalizedCanvasHeight = canvas.height / renderConfig.canvasScale;
|
||||
|
||||
if (isExporting && renderConfig.theme === "dark") {
|
||||
context.filter = THEME_FILTER;
|
||||
}
|
||||
|
||||
// Paint background
|
||||
if (typeof renderConfig.viewBackgroundColor === "string") {
|
||||
if (typeof renderConfig.canvasBackgroundColor === "string") {
|
||||
const hasTransparence =
|
||||
renderConfig.viewBackgroundColor === "transparent" ||
|
||||
renderConfig.viewBackgroundColor.length === 5 || // #RGBA
|
||||
renderConfig.viewBackgroundColor.length === 9 || // #RRGGBBA
|
||||
/(hsla|rgba)\(/.test(renderConfig.viewBackgroundColor);
|
||||
renderConfig.canvasBackgroundColor === "transparent" ||
|
||||
renderConfig.canvasBackgroundColor.length === 5 || // #RGBA
|
||||
renderConfig.canvasBackgroundColor.length === 9 || // #RRGGBBA
|
||||
/(hsla|rgba)\(/.test(renderConfig.canvasBackgroundColor);
|
||||
if (hasTransparence) {
|
||||
context.clearRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
|
||||
}
|
||||
context.save();
|
||||
context.fillStyle = renderConfig.viewBackgroundColor;
|
||||
context.fillStyle = renderConfig.canvasBackgroundColor;
|
||||
context.fillRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
|
||||
context.restore();
|
||||
} else {
|
||||
@ -796,7 +794,6 @@ const renderSceneThrottled = throttleRAF(
|
||||
(config: {
|
||||
elements: readonly NonDeletedExcalidrawElement[];
|
||||
appState: AppState;
|
||||
scale: number;
|
||||
rc: RoughCanvas;
|
||||
canvas: HTMLCanvasElement;
|
||||
renderConfig: RenderConfig;
|
||||
@ -813,7 +810,6 @@ export const renderScene = <T extends boolean = false>(
|
||||
config: {
|
||||
elements: readonly NonDeletedExcalidrawElement[];
|
||||
appState: AppState;
|
||||
scale: number;
|
||||
rc: RoughCanvas;
|
||||
canvas: HTMLCanvasElement;
|
||||
renderConfig: RenderConfig;
|
||||
|
@ -1,73 +1,447 @@
|
||||
import rough from "roughjs/bin/rough";
|
||||
import { NonDeletedExcalidrawElement } from "../element/types";
|
||||
import { NonDeletedExcalidrawElement, Theme } from "../element/types";
|
||||
import { getCommonBounds } from "../element/bounds";
|
||||
import { renderScene, renderSceneToSvg } from "../renderer/renderScene";
|
||||
import { distance } from "../utils";
|
||||
import { AppState, BinaryFiles } from "../types";
|
||||
import { DEFAULT_EXPORT_PADDING, SVG_NS, THEME_FILTER } from "../constants";
|
||||
import { getDefaultAppState } from "../appState";
|
||||
import {
|
||||
DEFAULT_BACKGROUND_COLOR,
|
||||
DEFAULT_EXPORT_PADDING,
|
||||
DEFAULT_ZOOM_VALUE,
|
||||
ENV,
|
||||
SVG_NS,
|
||||
THEME,
|
||||
THEME_FILTER,
|
||||
} from "../constants";
|
||||
import { serializeAsJSON } from "../data/json";
|
||||
import {
|
||||
getInitializedImageElements,
|
||||
updateImageCache,
|
||||
} from "../element/image";
|
||||
import { restoreAppState } from "../data/restore";
|
||||
|
||||
export const SVG_EXPORT_TAG = `<!-- svg-source:excalidraw -->`;
|
||||
|
||||
export const exportToCanvas = async (
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
appState: AppState,
|
||||
files: BinaryFiles,
|
||||
{
|
||||
exportBackground,
|
||||
exportPadding = DEFAULT_EXPORT_PADDING,
|
||||
viewBackgroundColor,
|
||||
}: {
|
||||
exportBackground: boolean;
|
||||
exportPadding?: number;
|
||||
viewBackgroundColor: string;
|
||||
},
|
||||
createCanvas: (
|
||||
export type ExportToCanvasData = {
|
||||
elements: readonly NonDeletedExcalidrawElement[];
|
||||
appState?: Partial<Omit<AppState, "offsetTop" | "offsetLeft">>;
|
||||
files: BinaryFiles | null;
|
||||
};
|
||||
|
||||
export type ExportToCanvasConfig = {
|
||||
theme?: Theme;
|
||||
/**
|
||||
* Canvas background. Valid values are:
|
||||
*
|
||||
* - `undefined` - the background of "appState.viewBackgroundColor" is used.
|
||||
* - `false` - no background is used (set to "transparent").
|
||||
* - `string` - should be a valid CSS color.
|
||||
*
|
||||
* @default undefined
|
||||
*/
|
||||
canvasBackgroundColor?: string | false;
|
||||
/**
|
||||
* Canvas padding in pixels. Affected by `scale`.
|
||||
*
|
||||
* When `fit` is set to `none`, padding is added to the content bounding box
|
||||
* (including if you set `width` or `height` or `maxWidthOrHeight` or
|
||||
* `widthOrHeight`).
|
||||
*
|
||||
* When `fit` set to `contain`, padding is subtracted from the content
|
||||
* bounding box (ensuring the size doesn't exceed the supplied values, with
|
||||
* the exeception of using alongside `scale` as noted above), and the padding
|
||||
* serves as a minimum distance between the content and the canvas edges, as
|
||||
* it may exceed the supplied padding value from one side or the other in
|
||||
* order to maintain the aspect ratio. It is recommended to set `position`
|
||||
* to `center` when using `fit=contain`.
|
||||
*
|
||||
* When `fit` is set to `cover`, padding is disabled (set to 0).
|
||||
*
|
||||
* When `fit` is set to `none` and either `width` or `height` or
|
||||
* `maxWidthOrHeight` is set, padding is simply adding to the bounding box
|
||||
* and the content may overflow the canvas, thus right or bottom padding
|
||||
* may be ignored.
|
||||
*
|
||||
* @default 0
|
||||
*/
|
||||
padding?: number;
|
||||
// -------------------------------------------------------------------------
|
||||
/**
|
||||
* Makes sure the canvas content fits into a frame of width/height no larger
|
||||
* than this value, while maintaining the aspect ratio.
|
||||
*
|
||||
* Final dimensions can get smaller/larger if used in conjunction with
|
||||
* `scale`.
|
||||
*/
|
||||
maxWidthOrHeight?: number;
|
||||
/**
|
||||
* Scale the canvas content to be excatly this many pixels wide/tall,
|
||||
* maintaining the aspect ratio.
|
||||
*
|
||||
* Cannot be used in conjunction with `maxWidthOrHeight`.
|
||||
*
|
||||
* Final dimensions can get smaller/larger if used in conjunction with
|
||||
* `scale`.
|
||||
*/
|
||||
widthOrHeight?: number;
|
||||
// -------------------------------------------------------------------------
|
||||
/**
|
||||
* Width of the frame. Supply `x` or `y` if you want to ofsset the canvas
|
||||
* content.
|
||||
*
|
||||
* If `width` omitted but `height` supplied, `width` is calculated from the
|
||||
* the content's bounding box to preserve the aspect ratio.
|
||||
*
|
||||
* Defaults to the content bounding box width when both `width` and `height`
|
||||
* are omitted.
|
||||
*/
|
||||
width?: number;
|
||||
/**
|
||||
* Height of the frame.
|
||||
*
|
||||
* If `height` omitted but `width` supplied, `height` is calculated from the
|
||||
* content's bounding box to preserve the aspect ratio.
|
||||
*
|
||||
* Defaults to the content bounding box height when both `width` and `height`
|
||||
* are omitted.
|
||||
*/
|
||||
height?: number;
|
||||
/**
|
||||
* Left canvas offset. By default the coordinate is relative to the canvas.
|
||||
* You can switch to content coordinates by setting `origin` to `content`.
|
||||
*
|
||||
* Defaults to the `x` postion of the content bounding box.
|
||||
*/
|
||||
x?: number;
|
||||
/**
|
||||
* Top canvas offset. By default the coordinate is relative to the canvas.
|
||||
* You can switch to content coordinates by setting `origin` to `content`.
|
||||
*
|
||||
* Defaults to the `y` postion of the content bounding box.
|
||||
*/
|
||||
y?: number;
|
||||
/**
|
||||
* Indicates the coordinate system of the `x` and `y` values.
|
||||
*
|
||||
* - `canvas` - `x` and `y` are relative to the canvas [0, 0] position.
|
||||
* - `content` - `x` and `y` are relative to the content bounding box.
|
||||
*
|
||||
* @default "canvas"
|
||||
*/
|
||||
origin?: "canvas" | "content";
|
||||
/**
|
||||
* If dimensions specified and `x` and `y` are not specified, this indicates
|
||||
* how the canvas should be scaled.
|
||||
*
|
||||
* Behavior aligns with the `object-fit` CSS property.
|
||||
*
|
||||
* - `none` - no scaling.
|
||||
* - `contain` - scale to fit the frame. Includes `padding`.
|
||||
* - `cover` - scale to fill the frame while maintaining aspect ratio. If
|
||||
* content overflows, it will be cropped.
|
||||
*
|
||||
* If `maxWidthOrHeight` or `widthOrHeight` is set, `fit` is ignored.
|
||||
*
|
||||
* @default "contain" unless `width`, `height`, `maxWidthOrHeight`, or
|
||||
* `widthOrHeight` is specified in which case `none` is the default (can be
|
||||
* changed). If `x` or `y` are specified, `none` is forced.
|
||||
*/
|
||||
fit?: "none" | "contain" | "cover";
|
||||
/**
|
||||
* When either `x` or `y` are not specified, indicates how the canvas should
|
||||
* be aligned on the respective axis.
|
||||
*
|
||||
* - `none` - canvas aligned to top left.
|
||||
* - `center` - canvas is centered on the axis which is not specified
|
||||
* (or both).
|
||||
*
|
||||
* If `maxWidthOrHeight` or `widthOrHeight` is set, `position` is ignored.
|
||||
*
|
||||
* @default "center"
|
||||
*/
|
||||
position?: "center" | "topLeft";
|
||||
// -------------------------------------------------------------------------
|
||||
/**
|
||||
* A multiplier to increase/decrease the frame dimensions
|
||||
* (content resolution).
|
||||
*
|
||||
* For example, if your canvas is 300x150 and you set scale to 2, the
|
||||
* resulting size will be 600x300.
|
||||
*
|
||||
* @default 1
|
||||
*/
|
||||
scale?: number;
|
||||
/**
|
||||
* If you need to suply your own canvas, e.g. in test environments or in
|
||||
* Node.js.
|
||||
*
|
||||
* Do not set `canvas.width/height` or modify the canvas context as that's
|
||||
* handled by Excalidraw.
|
||||
*
|
||||
* Defaults to `document.createElement("canvas")`.
|
||||
*/
|
||||
createCanvas?: () => HTMLCanvasElement;
|
||||
/**
|
||||
* If you want to supply `width`/`height` dynamically (or derive from the
|
||||
* content bounding box), you can use this function.
|
||||
*
|
||||
* Ignored if `maxWidthOrHeight`, `width`, or `height` is set.
|
||||
*/
|
||||
getDimensions?: (
|
||||
width: number,
|
||||
height: number,
|
||||
) => { canvas: HTMLCanvasElement; scale: number } = (width, height) => {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = width * appState.exportScale;
|
||||
canvas.height = height * appState.exportScale;
|
||||
return { canvas, scale: appState.exportScale };
|
||||
},
|
||||
) => {
|
||||
const [minX, minY, width, height] = getCanvasSize(elements, exportPadding);
|
||||
) => { width: number; height: number; scale?: number };
|
||||
};
|
||||
|
||||
const { canvas, scale = 1 } = createCanvas(width, height);
|
||||
/**
|
||||
* This API is usually used as a precursor to searializing to Blob or PNG,
|
||||
* but can also be used to create a canvas for other purposes.
|
||||
*/
|
||||
export const exportToCanvas = async ({
|
||||
data,
|
||||
config,
|
||||
}: {
|
||||
data: ExportToCanvasData;
|
||||
config?: ExportToCanvasConfig;
|
||||
}) => {
|
||||
// initialize defaults
|
||||
// ---------------------------------------------------------------------------
|
||||
const { elements, files } = data;
|
||||
|
||||
const defaultAppState = getDefaultAppState();
|
||||
const appState = restoreAppState(data.appState, null);
|
||||
|
||||
// clone
|
||||
const cfg = Object.assign({}, config);
|
||||
|
||||
cfg.fit =
|
||||
cfg.fit ??
|
||||
(cfg.width != null ||
|
||||
cfg.height != null ||
|
||||
cfg.maxWidthOrHeight != null ||
|
||||
cfg.widthOrHeight != null
|
||||
? "contain"
|
||||
: "none");
|
||||
|
||||
const containPadding = cfg.fit === "contain";
|
||||
|
||||
if (cfg.x != null || cfg.x != null) {
|
||||
cfg.fit = "none";
|
||||
}
|
||||
|
||||
if (cfg.fit === "cover") {
|
||||
if (cfg.padding && process.env.NODE_ENV !== ENV.PRODUCTION) {
|
||||
console.warn("`padding` is ignored when `fit` is set to `cover`");
|
||||
}
|
||||
cfg.padding = 0;
|
||||
}
|
||||
|
||||
cfg.padding = cfg.padding ?? 0;
|
||||
cfg.scale = cfg.scale ?? 1;
|
||||
|
||||
cfg.origin = cfg.origin ?? "canvas";
|
||||
cfg.position = cfg.position ?? "center";
|
||||
|
||||
if (cfg.maxWidthOrHeight != null && cfg.widthOrHeight != null) {
|
||||
if (process.env.NODE_ENV !== ENV.PRODUCTION) {
|
||||
console.warn("`maxWidthOrHeight` is ignored when `widthOrHeight` is set");
|
||||
}
|
||||
cfg.maxWidthOrHeight = undefined;
|
||||
}
|
||||
|
||||
if (
|
||||
(cfg.maxWidthOrHeight != null || cfg.width != null || cfg.height != null) &&
|
||||
cfg.getDimensions
|
||||
) {
|
||||
if (process.env.NODE_ENV !== ENV.PRODUCTION) {
|
||||
console.warn(
|
||||
"`getDimensions` is ignored when `width`, `height`, or `maxWidthOrHeight` is set",
|
||||
);
|
||||
}
|
||||
cfg.getDimensions = undefined;
|
||||
}
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// value used to scale the canvas context. By default, we use this to
|
||||
// make the canvas fit into the frame (e.g. for `cfg.fit` set to `contain`).
|
||||
// If `cfg.scale` is set, we multiply the resulting canvasScale by it to
|
||||
// scale the output further.
|
||||
let canvasScale = 1;
|
||||
|
||||
const origCanvasSize = getCanvasSize(elements);
|
||||
|
||||
// cfg.x = undefined;
|
||||
// cfg.y = undefined;
|
||||
|
||||
// variables for original content bounding box
|
||||
const [origX, origY, origWidth, origHeight] = origCanvasSize;
|
||||
// variables for target bounding box
|
||||
let [x, y, width, height] = origCanvasSize;
|
||||
|
||||
if (cfg.width != null) {
|
||||
width = cfg.width;
|
||||
|
||||
if (cfg.padding && containPadding) {
|
||||
width -= cfg.padding * 2;
|
||||
}
|
||||
|
||||
if (cfg.height) {
|
||||
height = cfg.height;
|
||||
if (cfg.padding && containPadding) {
|
||||
height -= cfg.padding * 2;
|
||||
}
|
||||
} else {
|
||||
// if height not specified, scale the original height to match the new
|
||||
// width while maintaining aspect ratio
|
||||
height *= width / origWidth;
|
||||
}
|
||||
} else if (cfg.height != null) {
|
||||
height = cfg.height;
|
||||
|
||||
if (cfg.padding && containPadding) {
|
||||
height -= cfg.padding * 2;
|
||||
}
|
||||
// width not specified, so scale the original width to match the new
|
||||
// height while maintaining aspect ratio
|
||||
width *= height / origHeight;
|
||||
}
|
||||
|
||||
if (cfg.maxWidthOrHeight != null || cfg.widthOrHeight != null) {
|
||||
if (containPadding && cfg.padding) {
|
||||
if (cfg.maxWidthOrHeight != null) {
|
||||
cfg.maxWidthOrHeight -= cfg.padding * 2;
|
||||
} else if (cfg.widthOrHeight != null) {
|
||||
cfg.widthOrHeight -= cfg.padding * 2;
|
||||
}
|
||||
}
|
||||
|
||||
const max = Math.max(width, height);
|
||||
if (cfg.widthOrHeight != null) {
|
||||
// calculate by how much do we need to scale the canvas to fit into the
|
||||
// target dimension (e.g. target: max 50px, actual: 70x100px => scale: 0.5)
|
||||
canvasScale = cfg.widthOrHeight / max;
|
||||
} else if (cfg.maxWidthOrHeight != null) {
|
||||
canvasScale = cfg.maxWidthOrHeight < max ? cfg.maxWidthOrHeight / max : 1;
|
||||
}
|
||||
|
||||
width *= canvasScale;
|
||||
height *= canvasScale;
|
||||
} else if (cfg.getDimensions) {
|
||||
const ret = cfg.getDimensions(width, height);
|
||||
|
||||
width = ret.width;
|
||||
height = ret.height;
|
||||
cfg.scale = ret.scale ?? cfg.scale;
|
||||
} else if (
|
||||
containPadding &&
|
||||
cfg.padding &&
|
||||
cfg.width == null &&
|
||||
cfg.height == null
|
||||
) {
|
||||
const whRatio = width / height;
|
||||
width -= cfg.padding * 2;
|
||||
height -= (cfg.padding * 2) / whRatio;
|
||||
}
|
||||
|
||||
if (
|
||||
(cfg.fit === "contain" && !cfg.maxWidthOrHeight) ||
|
||||
(containPadding && cfg.padding)
|
||||
) {
|
||||
if (cfg.fit === "contain") {
|
||||
const wRatio = width / origWidth;
|
||||
const hRatio = height / origHeight;
|
||||
// scale the orig canvas to fit in the target frame
|
||||
canvasScale = Math.min(wRatio, hRatio);
|
||||
} else {
|
||||
const wRatio = (width - cfg.padding * 2) / width;
|
||||
const hRatio = (height - cfg.padding * 2) / height;
|
||||
canvasScale = Math.min(wRatio, hRatio);
|
||||
}
|
||||
} else if (cfg.fit === "cover") {
|
||||
const wRatio = width / origWidth;
|
||||
const hRatio = height / origHeight;
|
||||
// scale the orig canvas to fill the the target frame
|
||||
// (opposite of "contain")
|
||||
canvasScale = Math.max(wRatio, hRatio);
|
||||
}
|
||||
|
||||
x = cfg.x ?? origX;
|
||||
y = cfg.y ?? origY;
|
||||
|
||||
// if we switch to "content" coords, we need to offset cfg-supplied
|
||||
// coords by the x/y of content bounding box
|
||||
if (cfg.origin === "content") {
|
||||
if (cfg.x != null) {
|
||||
x += origX;
|
||||
}
|
||||
if (cfg.y != null) {
|
||||
y += origY;
|
||||
}
|
||||
}
|
||||
|
||||
// Centering the content to the frame.
|
||||
// We divide width/height by canvasScale so that we calculate in the original
|
||||
// aspect ratio dimensions.
|
||||
if (cfg.position === "center") {
|
||||
x -=
|
||||
width / canvasScale / 2 -
|
||||
(cfg.x == null ? origWidth : width + cfg.padding * 2) / 2;
|
||||
y -=
|
||||
height / canvasScale / 2 -
|
||||
(cfg.y == null ? origHeight : height + cfg.padding * 2) / 2;
|
||||
}
|
||||
|
||||
const canvas = cfg.createCanvas
|
||||
? cfg.createCanvas()
|
||||
: document.createElement("canvas");
|
||||
|
||||
// rescale padding based on current canvasScale factor so that the resulting
|
||||
// padding is kept the same as supplied by user (with the exception of
|
||||
// `cfg.scale` being set, which also scales the padding)
|
||||
const normalizedPadding = cfg.padding / canvasScale;
|
||||
|
||||
// scale the whole frame by cfg.scale (on top of whatever canvasScale we
|
||||
// calculated above)
|
||||
canvasScale *= cfg.scale;
|
||||
|
||||
width *= cfg.scale;
|
||||
height *= cfg.scale;
|
||||
|
||||
canvas.width = width + cfg.padding * 2 * cfg.scale;
|
||||
canvas.height = height + cfg.padding * 2 * cfg.scale;
|
||||
|
||||
const { imageCache } = await updateImageCache({
|
||||
imageCache: new Map(),
|
||||
fileIds: getInitializedImageElements(elements).map(
|
||||
(element) => element.fileId,
|
||||
),
|
||||
files,
|
||||
files: files || {},
|
||||
});
|
||||
|
||||
// console.log(elements, width, height, cfg, canvasScale);
|
||||
|
||||
renderScene({
|
||||
elements,
|
||||
appState,
|
||||
scale,
|
||||
appState: { ...appState, width, height, offsetLeft: 0, offsetTop: 0 },
|
||||
rc: rough.canvas(canvas),
|
||||
canvas,
|
||||
renderConfig: {
|
||||
viewBackgroundColor: exportBackground ? viewBackgroundColor : null,
|
||||
scrollX: -minX + exportPadding,
|
||||
scrollY: -minY + exportPadding,
|
||||
zoom: defaultAppState.zoom,
|
||||
canvasBackgroundColor:
|
||||
cfg.canvasBackgroundColor === false
|
||||
? // null indicates transparent background
|
||||
null
|
||||
: cfg.canvasBackgroundColor ||
|
||||
appState.viewBackgroundColor ||
|
||||
DEFAULT_BACKGROUND_COLOR,
|
||||
scrollX: -x + normalizedPadding,
|
||||
scrollY: -y + normalizedPadding,
|
||||
canvasScale,
|
||||
zoom: { value: DEFAULT_ZOOM_VALUE },
|
||||
remotePointerViewportCoords: {},
|
||||
remoteSelectedElementIds: {},
|
||||
shouldCacheIgnoreZoom: false,
|
||||
remotePointerUsernames: {},
|
||||
remotePointerUserStates: {},
|
||||
theme: appState.exportWithDarkMode ? "dark" : "light",
|
||||
theme: cfg.theme || THEME.LIGHT,
|
||||
imageCache,
|
||||
renderScrollbars: false,
|
||||
renderSelection: false,
|
||||
@ -114,7 +488,7 @@ export const exportToSvg = async (
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
const [minX, minY, width, height] = getCanvasSize(elements, exportPadding);
|
||||
const [minX, minY, width, height] = getCanvasSize(elements);
|
||||
|
||||
// initialize SVG root
|
||||
const svgRoot = document.createElementNS(SVG_NS, "svg");
|
||||
@ -178,25 +552,12 @@ export const exportToSvg = async (
|
||||
};
|
||||
|
||||
// calculate smallest area to fit the contents in
|
||||
const getCanvasSize = (
|
||||
export const getCanvasSize = (
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
exportPadding: number,
|
||||
): [number, number, number, number] => {
|
||||
): [minX: number, minY: number, width: number, height: number] => {
|
||||
const [minX, minY, maxX, maxY] = getCommonBounds(elements);
|
||||
const width = distance(minX, maxX) + exportPadding * 2;
|
||||
const height = distance(minY, maxY) + exportPadding + exportPadding;
|
||||
const width = distance(minX, maxX);
|
||||
const height = distance(minY, maxY);
|
||||
|
||||
return [minX, minY, width, height];
|
||||
};
|
||||
|
||||
export const getExportSize = (
|
||||
elements: readonly NonDeletedExcalidrawElement[],
|
||||
exportPadding: number,
|
||||
scale: number,
|
||||
): [number, number] => {
|
||||
const [, , width, height] = getCanvasSize(elements, exportPadding).map(
|
||||
(dimension) => Math.trunc(dimension * scale),
|
||||
);
|
||||
|
||||
return [width, height];
|
||||
};
|
||||
|
@ -2,15 +2,23 @@ import { ExcalidrawTextElement } from "../element/types";
|
||||
import { AppClassProperties, AppState } from "../types";
|
||||
|
||||
export type RenderConfig = {
|
||||
// AppState values
|
||||
// canvas related (AppState)
|
||||
// ---------------------------------------------------------------------------
|
||||
scrollX: AppState["scrollX"];
|
||||
scrollY: AppState["scrollY"];
|
||||
/** null indicates transparent bg */
|
||||
viewBackgroundColor: AppState["viewBackgroundColor"] | null;
|
||||
canvasBackgroundColor: AppState["viewBackgroundColor"] | null;
|
||||
zoom: AppState["zoom"];
|
||||
shouldCacheIgnoreZoom: AppState["shouldCacheIgnoreZoom"];
|
||||
theme: AppState["theme"];
|
||||
/**
|
||||
* canvas scale factor. Not related to zoom. In browsers, it's the
|
||||
* devicePixelRatio. For export, it's the `appState.exportScale`
|
||||
* (user setting) or whatever scale you want to use when exporting elsewhere.
|
||||
*
|
||||
* Bigger the scale, the more pixels (=quality).
|
||||
*/
|
||||
canvasScale: number;
|
||||
// collab-related state
|
||||
// ---------------------------------------------------------------------------
|
||||
remotePointerViewportCoords: { [id: string]: { x: number; y: number } };
|
||||
|
@ -3,6 +3,7 @@ import { diagramFactory } from "../fixtures/diagramFixture";
|
||||
import * as mockedSceneExportUtils from "../../scene/export";
|
||||
import { MIME_TYPES } from "../../constants";
|
||||
|
||||
import { exportToCanvas } from "../../scene/export";
|
||||
jest.mock("../../scene/export", () => ({
|
||||
__esmodule: true,
|
||||
...jest.requireActual("../../scene/export"),
|
||||
@ -13,8 +14,8 @@ describe("exportToCanvas", () => {
|
||||
const EXPORT_PADDING = 10;
|
||||
|
||||
it("with default arguments", async () => {
|
||||
const canvas = await utils.exportToCanvas({
|
||||
...diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
|
||||
const canvas = await exportToCanvas({
|
||||
data: diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
|
||||
});
|
||||
|
||||
expect(canvas.width).toBe(100 + 2 * EXPORT_PADDING);
|
||||
@ -22,9 +23,13 @@ describe("exportToCanvas", () => {
|
||||
});
|
||||
|
||||
it("when custom width and height", async () => {
|
||||
const canvas = await utils.exportToCanvas({
|
||||
const canvas = await exportToCanvas({
|
||||
data: {
|
||||
...diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
|
||||
},
|
||||
config: {
|
||||
getDimensions: () => ({ width: 200, height: 200, scale: 1 }),
|
||||
},
|
||||
});
|
||||
|
||||
expect(canvas.width).toBe(200);
|
||||
@ -38,12 +43,17 @@ describe("exportToBlob", () => {
|
||||
|
||||
it("should change image/jpg to image/jpeg", async () => {
|
||||
const blob = await utils.exportToBlob({
|
||||
data: {
|
||||
...diagramFactory(),
|
||||
|
||||
appState: {
|
||||
exportBackground: true,
|
||||
},
|
||||
},
|
||||
config: {
|
||||
getDimensions: (width, height) => ({ width, height, scale: 1 }),
|
||||
// testing typo in MIME type (jpg → jpeg)
|
||||
mimeType: "image/jpg",
|
||||
appState: {
|
||||
exportBackground: true,
|
||||
},
|
||||
});
|
||||
expect(blob?.type).toBe(MIME_TYPES.jpg);
|
||||
@ -51,7 +61,7 @@ describe("exportToBlob", () => {
|
||||
|
||||
it("should default to image/png", async () => {
|
||||
const blob = await utils.exportToBlob({
|
||||
...diagramFactory(),
|
||||
data: diagramFactory(),
|
||||
});
|
||||
expect(blob?.type).toBe(MIME_TYPES.png);
|
||||
});
|
||||
@ -62,9 +72,11 @@ describe("exportToBlob", () => {
|
||||
.mockImplementationOnce(() => void 0);
|
||||
|
||||
await utils.exportToBlob({
|
||||
...diagramFactory(),
|
||||
data: diagramFactory(),
|
||||
config: {
|
||||
mimeType: MIME_TYPES.png,
|
||||
quality: 1,
|
||||
},
|
||||
});
|
||||
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
@ -82,7 +94,7 @@ describe("exportToSvg", () => {
|
||||
|
||||
it("with default arguments", async () => {
|
||||
await utils.exportToSvg({
|
||||
...diagramFactory({
|
||||
data: diagramFactory({
|
||||
overrides: { appState: void 0 },
|
||||
}),
|
||||
});
|
||||
@ -98,7 +110,7 @@ describe("exportToSvg", () => {
|
||||
|
||||
it("with deleted elements", async () => {
|
||||
await utils.exportToSvg({
|
||||
...diagramFactory({
|
||||
data: diagramFactory({
|
||||
overrides: { appState: void 0 },
|
||||
elementOverrides: { isDeleted: true },
|
||||
}),
|
||||
@ -109,8 +121,10 @@ describe("exportToSvg", () => {
|
||||
|
||||
it("with exportPadding", async () => {
|
||||
await utils.exportToSvg({
|
||||
...diagramFactory({ overrides: { appState: { name: "diagram name" } } }),
|
||||
exportPadding: 0,
|
||||
data: diagramFactory({
|
||||
overrides: { appState: { name: "diagram name" } },
|
||||
}),
|
||||
config: { padding: 0 },
|
||||
});
|
||||
|
||||
expect(passedElements().length).toBe(3);
|
||||
@ -121,7 +135,7 @@ describe("exportToSvg", () => {
|
||||
|
||||
it("with exportEmbedScene", async () => {
|
||||
await utils.exportToSvg({
|
||||
...diagramFactory({
|
||||
data: diagramFactory({
|
||||
overrides: {
|
||||
appState: { name: "diagram name", exportEmbedScene: true },
|
||||
},
|
||||
|
@ -16,6 +16,7 @@ describe("embedding scene data", () => {
|
||||
const sourceElements = [rectangle, ellipse];
|
||||
|
||||
const svgNode = await utils.exportToSvg({
|
||||
data: {
|
||||
elements: sourceElements,
|
||||
appState: {
|
||||
viewBackgroundColor: "#ffffff",
|
||||
@ -23,6 +24,7 @@ describe("embedding scene data", () => {
|
||||
exportEmbedScene: true,
|
||||
},
|
||||
files: null,
|
||||
},
|
||||
});
|
||||
|
||||
const svg = svgNode.outerHTML;
|
||||
@ -46,7 +48,7 @@ describe("embedding scene data", () => {
|
||||
const sourceElements = [rectangle, ellipse];
|
||||
|
||||
const blob = await utils.exportToBlob({
|
||||
mimeType: "image/png",
|
||||
data: {
|
||||
elements: sourceElements,
|
||||
appState: {
|
||||
viewBackgroundColor: "#ffffff",
|
||||
@ -54,6 +56,10 @@ describe("embedding scene data", () => {
|
||||
exportEmbedScene: true,
|
||||
},
|
||||
files: null,
|
||||
},
|
||||
config: {
|
||||
mimeType: "image/png",
|
||||
},
|
||||
});
|
||||
|
||||
const parsedString = await decodePngMetadata(blob);
|
||||
|
Loading…
x
Reference in New Issue
Block a user