rewrite exportToCanvas and start deduplicating export utils
This commit is contained in:
parent
33ab88926f
commit
41de1fa951
@ -8,7 +8,7 @@ import {
|
|||||||
} from "../clipboard";
|
} from "../clipboard";
|
||||||
import { actionDeleteSelected } from "./actionDeleteSelected";
|
import { actionDeleteSelected } from "./actionDeleteSelected";
|
||||||
import { getSelectedElements } from "../scene/selection";
|
import { getSelectedElements } from "../scene/selection";
|
||||||
import { exportCanvas } from "../data/index";
|
import { exportAsImage } from "../data/index";
|
||||||
import { getNonDeletedElements, isTextElement } from "../element";
|
import { getNonDeletedElements, isTextElement } from "../element";
|
||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
|
|
||||||
@ -78,7 +78,7 @@ export const actionCopyAsSvg = register({
|
|||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
try {
|
try {
|
||||||
await exportCanvas(
|
await exportAsImage(
|
||||||
"clipboard-svg",
|
"clipboard-svg",
|
||||||
selectedElements.length
|
selectedElements.length
|
||||||
? selectedElements
|
? selectedElements
|
||||||
@ -122,7 +122,7 @@ export const actionCopyAsPng = register({
|
|||||||
true,
|
true,
|
||||||
);
|
);
|
||||||
try {
|
try {
|
||||||
await exportCanvas(
|
await exportAsImage(
|
||||||
"clipboard",
|
"clipboard",
|
||||||
selectedElements.length
|
selectedElements.length
|
||||||
? selectedElements
|
? selectedElements
|
||||||
|
@ -1347,14 +1347,14 @@ class App extends React.Component<AppProps, AppState> {
|
|||||||
{
|
{
|
||||||
elements: renderingElements,
|
elements: renderingElements,
|
||||||
appState: this.state,
|
appState: this.state,
|
||||||
scale: window.devicePixelRatio,
|
|
||||||
rc: this.rc!,
|
rc: this.rc!,
|
||||||
canvas: this.canvas!,
|
canvas: this.canvas!,
|
||||||
renderConfig: {
|
renderConfig: {
|
||||||
|
canvasScale: window.devicePixelRatio,
|
||||||
selectionColor,
|
selectionColor,
|
||||||
scrollX: this.state.scrollX,
|
scrollX: this.state.scrollX,
|
||||||
scrollY: this.state.scrollY,
|
scrollY: this.state.scrollY,
|
||||||
viewBackgroundColor: this.state.viewBackgroundColor,
|
canvasBackgroundColor: this.state.viewBackgroundColor,
|
||||||
zoom: this.state.zoom,
|
zoom: this.state.zoom,
|
||||||
remotePointerViewportCoords: pointerViewportCoords,
|
remotePointerViewportCoords: pointerViewportCoords,
|
||||||
remotePointerButton: cursorButton,
|
remotePointerButton: cursorButton,
|
||||||
|
@ -99,10 +99,18 @@ const ImageExportModal = ({
|
|||||||
if (!previewNode) {
|
if (!previewNode) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
exportToCanvas(exportedElements, appState, files, {
|
exportToCanvas({
|
||||||
exportBackground,
|
data: {
|
||||||
viewBackgroundColor,
|
elements: exportedElements,
|
||||||
exportPadding,
|
appState,
|
||||||
|
files,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
canvasBackgroundColor: !exportBackground ? false : viewBackgroundColor,
|
||||||
|
padding: exportPadding,
|
||||||
|
theme: appState.exportWithDarkMode ? "dark" : "light",
|
||||||
|
scale: appState.exportScale,
|
||||||
|
},
|
||||||
})
|
})
|
||||||
.then((canvas) => {
|
.then((canvas) => {
|
||||||
setRenderError(null);
|
setRenderError(null);
|
||||||
|
@ -2,7 +2,7 @@ import clsx from "clsx";
|
|||||||
import React from "react";
|
import React from "react";
|
||||||
import { ActionManager } from "../actions/manager";
|
import { ActionManager } from "../actions/manager";
|
||||||
import { CLASSES, LIBRARY_SIDEBAR_WIDTH } from "../constants";
|
import { CLASSES, LIBRARY_SIDEBAR_WIDTH } from "../constants";
|
||||||
import { exportCanvas } from "../data";
|
import { exportAsImage } from "../data";
|
||||||
import { isTextElement, showSelectedShapeActions } from "../element";
|
import { isTextElement, showSelectedShapeActions } from "../element";
|
||||||
import { NonDeletedExcalidrawElement } from "../element/types";
|
import { NonDeletedExcalidrawElement } from "../element/types";
|
||||||
import { Language, t } from "../i18n";
|
import { Language, t } from "../i18n";
|
||||||
@ -153,7 +153,7 @@ const LayerUI = ({
|
|||||||
(type: ExportType): ExportCB =>
|
(type: ExportType): ExportCB =>
|
||||||
async (exportedElements) => {
|
async (exportedElements) => {
|
||||||
trackEvent("export", type, "ui");
|
trackEvent("export", type, "ui");
|
||||||
const fileHandle = await exportCanvas(
|
const fileHandle = await exportAsImage(
|
||||||
type,
|
type,
|
||||||
exportedElements,
|
exportedElements,
|
||||||
appState,
|
appState,
|
||||||
|
@ -5,7 +5,6 @@ import { Dialog } from "./Dialog";
|
|||||||
import { t } from "../i18n";
|
import { t } from "../i18n";
|
||||||
|
|
||||||
import { AppState, LibraryItems, LibraryItem } from "../types";
|
import { AppState, LibraryItems, LibraryItem } from "../types";
|
||||||
import { exportToCanvas } from "../packages/utils";
|
|
||||||
import {
|
import {
|
||||||
EXPORT_DATA_TYPES,
|
EXPORT_DATA_TYPES,
|
||||||
EXPORT_SOURCE,
|
EXPORT_SOURCE,
|
||||||
@ -19,6 +18,7 @@ import SingleLibraryItem from "./SingleLibraryItem";
|
|||||||
import { canvasToBlob, resizeImageFile } from "../data/blob";
|
import { canvasToBlob, resizeImageFile } from "../data/blob";
|
||||||
import { chunk } from "../utils";
|
import { chunk } from "../utils";
|
||||||
import DialogActionButton from "./DialogActionButton";
|
import DialogActionButton from "./DialogActionButton";
|
||||||
|
import { exportToCanvas } from "../scene/export";
|
||||||
|
|
||||||
interface PublishLibraryDataParams {
|
interface PublishLibraryDataParams {
|
||||||
authorName: string;
|
authorName: string;
|
||||||
@ -85,9 +85,13 @@ const generatePreviewImage = async (libraryItems: LibraryItems) => {
|
|||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
for (const [index, item] of libraryItems.entries()) {
|
for (const [index, item] of libraryItems.entries()) {
|
||||||
const itemCanvas = await exportToCanvas({
|
const itemCanvas = await exportToCanvas({
|
||||||
elements: item.elements,
|
data: {
|
||||||
files: null,
|
elements: item.elements,
|
||||||
maxWidthOrHeight: BOX_SIZE,
|
files: null,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
maxWidthOrHeight: BOX_SIZE,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const { width, height } = itemCanvas;
|
const { width, height } = itemCanvas;
|
||||||
|
@ -31,13 +31,15 @@ const SingleLibraryItem = ({
|
|||||||
}
|
}
|
||||||
(async () => {
|
(async () => {
|
||||||
const svg = await exportToSvg({
|
const svg = await exportToSvg({
|
||||||
elements: libItem.elements,
|
data: {
|
||||||
appState: {
|
elements: libItem.elements,
|
||||||
...appState,
|
appState: {
|
||||||
viewBackgroundColor: oc.white,
|
...appState,
|
||||||
exportBackground: true,
|
viewBackgroundColor: oc.white,
|
||||||
|
exportBackground: true,
|
||||||
|
},
|
||||||
|
files: null,
|
||||||
},
|
},
|
||||||
files: null,
|
|
||||||
});
|
});
|
||||||
node.innerHTML = svg.outerHTML;
|
node.innerHTML = svg.outerHTML;
|
||||||
})();
|
})();
|
||||||
|
@ -15,7 +15,7 @@ import { serializeAsJSON } from "./json";
|
|||||||
export { loadFromBlob } from "./blob";
|
export { loadFromBlob } from "./blob";
|
||||||
export { loadFromJSON, saveAsJSON } from "./json";
|
export { loadFromJSON, saveAsJSON } from "./json";
|
||||||
|
|
||||||
export const exportCanvas = async (
|
export const exportAsImage = async (
|
||||||
type: Omit<ExportType, "backend">,
|
type: Omit<ExportType, "backend">,
|
||||||
elements: readonly NonDeletedExcalidrawElement[],
|
elements: readonly NonDeletedExcalidrawElement[],
|
||||||
appState: AppState,
|
appState: AppState,
|
||||||
@ -66,10 +66,18 @@ export const exportCanvas = async (
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const tempCanvas = await exportToCanvas(elements, appState, files, {
|
const tempCanvas = await exportToCanvas({
|
||||||
exportBackground,
|
data: {
|
||||||
viewBackgroundColor,
|
elements,
|
||||||
exportPadding,
|
appState,
|
||||||
|
files,
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
canvasBackgroundColor: !exportBackground ? false : viewBackgroundColor,
|
||||||
|
padding: exportPadding,
|
||||||
|
theme: appState.exportWithDarkMode ? "dark" : "light",
|
||||||
|
scale: appState.exportScale,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
tempCanvas.style.display = "none";
|
tempCanvas.style.display = "none";
|
||||||
document.body.appendChild(tempCanvas);
|
document.body.appendChild(tempCanvas);
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import { ExcalidrawElement } from "../element/types";
|
import { ExcalidrawElement } from "../element/types";
|
||||||
import { AppState, BinaryFiles } from "../types";
|
import { AppState, BinaryFiles } from "../types";
|
||||||
import { exportCanvas } from ".";
|
import { exportAsImage } from ".";
|
||||||
import { getNonDeletedElements } from "../element";
|
import { getNonDeletedElements } from "../element";
|
||||||
import { getFileHandleType, isImageFileHandleType } from "./blob";
|
import { getFileHandleType, isImageFileHandleType } from "./blob";
|
||||||
|
|
||||||
@ -23,7 +23,7 @@ export const resaveAsImageWithScene = async (
|
|||||||
exportEmbedScene: true,
|
exportEmbedScene: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
await exportCanvas(
|
await exportAsImage(
|
||||||
fileHandleType,
|
fileHandleType,
|
||||||
getNonDeletedElements(elements),
|
getNonDeletedElements(elements),
|
||||||
appState,
|
appState,
|
||||||
|
@ -57,22 +57,21 @@ const elements = [
|
|||||||
registerFont("./public/Virgil.woff2", { family: "Virgil" });
|
registerFont("./public/Virgil.woff2", { family: "Virgil" });
|
||||||
registerFont("./public/Cascadia.woff2", { family: "Cascadia" });
|
registerFont("./public/Cascadia.woff2", { family: "Cascadia" });
|
||||||
|
|
||||||
const canvas = exportToCanvas(
|
const canvas = exportToCanvas({
|
||||||
elements as any,
|
data: {
|
||||||
{
|
elements: elements as any,
|
||||||
...getDefaultAppState(),
|
appState: {
|
||||||
offsetTop: 0,
|
...getDefaultAppState(),
|
||||||
offsetLeft: 0,
|
width: 0,
|
||||||
width: 0,
|
height: 0,
|
||||||
height: 0,
|
},
|
||||||
|
files: {}, // files
|
||||||
},
|
},
|
||||||
{}, // files
|
config: {
|
||||||
{
|
canvasBackgroundColor: "#ffffff",
|
||||||
exportBackground: true,
|
createCanvas,
|
||||||
viewBackgroundColor: "#ffffff",
|
|
||||||
},
|
},
|
||||||
createCanvas,
|
});
|
||||||
);
|
|
||||||
|
|
||||||
const fs = require("fs");
|
const fs = require("fs");
|
||||||
const out = fs.createWriteStream("test.png");
|
const out = fs.createWriteStream("test.png");
|
||||||
|
@ -252,10 +252,12 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
await exportToClipboard({
|
await exportToClipboard({
|
||||||
elements: excalidrawAPI.getSceneElements(),
|
data: {
|
||||||
appState: excalidrawAPI.getAppState(),
|
elements: excalidrawAPI.getSceneElements(),
|
||||||
files: excalidrawAPI.getFiles(),
|
appState: excalidrawAPI.getAppState(),
|
||||||
type,
|
files: excalidrawAPI.getFiles(),
|
||||||
|
},
|
||||||
|
type: "json",
|
||||||
});
|
});
|
||||||
window.alert(`Copied to clipboard as ${type} successfully`);
|
window.alert(`Copied to clipboard as ${type} successfully`);
|
||||||
};
|
};
|
||||||
@ -743,15 +745,17 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const svg = await exportToSvg({
|
const svg = await exportToSvg({
|
||||||
elements: excalidrawAPI?.getSceneElements(),
|
data: {
|
||||||
appState: {
|
elements: excalidrawAPI?.getSceneElements(),
|
||||||
...initialData.appState,
|
appState: {
|
||||||
exportWithDarkMode,
|
...initialData.appState,
|
||||||
exportEmbedScene,
|
exportWithDarkMode,
|
||||||
width: 300,
|
exportEmbedScene,
|
||||||
height: 100,
|
width: 300,
|
||||||
|
height: 100,
|
||||||
|
},
|
||||||
|
files: excalidrawAPI?.getFiles(),
|
||||||
},
|
},
|
||||||
files: excalidrawAPI?.getFiles(),
|
|
||||||
});
|
});
|
||||||
appRef.current.querySelector(".export-svg").innerHTML =
|
appRef.current.querySelector(".export-svg").innerHTML =
|
||||||
svg.outerHTML;
|
svg.outerHTML;
|
||||||
@ -767,14 +771,18 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const blob = await exportToBlob({
|
const blob = await exportToBlob({
|
||||||
elements: excalidrawAPI?.getSceneElements(),
|
data: {
|
||||||
mimeType: "image/png",
|
elements: excalidrawAPI?.getSceneElements(),
|
||||||
appState: {
|
appState: {
|
||||||
...initialData.appState,
|
...initialData.appState,
|
||||||
exportEmbedScene,
|
exportEmbedScene,
|
||||||
exportWithDarkMode,
|
exportWithDarkMode,
|
||||||
|
},
|
||||||
|
files: excalidrawAPI?.getFiles(),
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
mimeType: "image/png",
|
||||||
},
|
},
|
||||||
files: excalidrawAPI?.getFiles(),
|
|
||||||
});
|
});
|
||||||
setBlobUrl(window.URL.createObjectURL(blob));
|
setBlobUrl(window.URL.createObjectURL(blob));
|
||||||
}}
|
}}
|
||||||
@ -791,12 +799,14 @@ export default function App({ appTitle, useCustom, customArgs }: AppProps) {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
const canvas = await exportToCanvas({
|
const canvas = await exportToCanvas({
|
||||||
elements: excalidrawAPI.getSceneElements(),
|
data: {
|
||||||
appState: {
|
elements: excalidrawAPI.getSceneElements(),
|
||||||
...initialData.appState,
|
appState: {
|
||||||
exportWithDarkMode,
|
...initialData.appState,
|
||||||
|
exportWithDarkMode,
|
||||||
|
},
|
||||||
|
files: excalidrawAPI.getFiles(),
|
||||||
},
|
},
|
||||||
files: excalidrawAPI.getFiles(),
|
|
||||||
});
|
});
|
||||||
const ctx = canvas.getContext("2d")!;
|
const ctx = canvas.getContext("2d")!;
|
||||||
ctx.font = "30px Virgil";
|
ctx.font = "30px Virgil";
|
||||||
|
@ -206,7 +206,6 @@ export {
|
|||||||
restoreLibraryItems,
|
restoreLibraryItems,
|
||||||
} from "../../data/restore";
|
} from "../../data/restore";
|
||||||
export {
|
export {
|
||||||
exportToCanvas,
|
|
||||||
exportToBlob,
|
exportToBlob,
|
||||||
exportToSvg,
|
exportToSvg,
|
||||||
serializeAsJSON,
|
serializeAsJSON,
|
||||||
@ -245,3 +244,5 @@ export { MainMenu };
|
|||||||
export { useDevice } from "../../components/App";
|
export { useDevice } from "../../components/App";
|
||||||
export { WelcomeScreen };
|
export { WelcomeScreen };
|
||||||
export { LiveCollaborationTrigger };
|
export { LiveCollaborationTrigger };
|
||||||
|
|
||||||
|
export { exportToCanvas } from "../../scene/export";
|
||||||
|
@ -1,13 +1,13 @@
|
|||||||
import {
|
import {
|
||||||
exportToCanvas as _exportToCanvas,
|
exportToCanvas,
|
||||||
|
ExportToCanvasConfig,
|
||||||
|
ExportToCanvasData,
|
||||||
exportToSvg as _exportToSvg,
|
exportToSvg as _exportToSvg,
|
||||||
} from "../scene/export";
|
} from "../scene/export";
|
||||||
import { getDefaultAppState } from "../appState";
|
import { getDefaultAppState } from "../appState";
|
||||||
import { AppState, BinaryFiles } from "../types";
|
|
||||||
import { ExcalidrawElement, NonDeleted } from "../element/types";
|
|
||||||
import { getNonDeletedElements } from "../element";
|
import { getNonDeletedElements } from "../element";
|
||||||
import { restore } from "../data/restore";
|
import { restore } from "../data/restore";
|
||||||
import { MIME_TYPES } from "../constants";
|
import { DEFAULT_BACKGROUND_COLOR, MIME_TYPES } from "../constants";
|
||||||
import { encodePngMetadata } from "../data/image";
|
import { encodePngMetadata } from "../data/image";
|
||||||
import { serializeAsJSON } from "../data/json";
|
import { serializeAsJSON } from "../data/json";
|
||||||
import {
|
import {
|
||||||
@ -18,82 +18,24 @@ import {
|
|||||||
|
|
||||||
export { MIME_TYPES };
|
export { MIME_TYPES };
|
||||||
|
|
||||||
type ExportOpts = {
|
type ExportToBlobConfig = ExportToCanvasConfig & {
|
||||||
elements: readonly NonDeleted<ExcalidrawElement>[];
|
mimeType?: string;
|
||||||
appState?: Partial<Omit<AppState, "offsetTop" | "offsetLeft">>;
|
quality?: number;
|
||||||
files: BinaryFiles | null;
|
|
||||||
maxWidthOrHeight?: number;
|
|
||||||
getDimensions?: (
|
|
||||||
width: number,
|
|
||||||
height: number,
|
|
||||||
) => { width: number; height: number; scale?: number };
|
|
||||||
};
|
};
|
||||||
|
|
||||||
export const exportToCanvas = ({
|
type ExportToSvgConfig = Pick<
|
||||||
elements,
|
ExportToCanvasConfig,
|
||||||
appState,
|
"canvasBackgroundColor" | "padding" | "theme"
|
||||||
files,
|
>;
|
||||||
maxWidthOrHeight,
|
|
||||||
getDimensions,
|
|
||||||
exportPadding,
|
|
||||||
}: ExportOpts & {
|
|
||||||
exportPadding?: number;
|
|
||||||
}) => {
|
|
||||||
const { elements: restoredElements, appState: restoredAppState } = restore(
|
|
||||||
{ elements, appState },
|
|
||||||
null,
|
|
||||||
null,
|
|
||||||
);
|
|
||||||
const { exportBackground, viewBackgroundColor } = restoredAppState;
|
|
||||||
return _exportToCanvas(
|
|
||||||
getNonDeletedElements(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) {
|
export const exportToBlob = async ({
|
||||||
if (typeof getDimensions === "function") {
|
data,
|
||||||
console.warn(
|
config,
|
||||||
"`getDimensions()` is ignored when `maxWidthOrHeight` is supplied.",
|
}: {
|
||||||
);
|
data: ExportToCanvasData;
|
||||||
}
|
config?: ExportToBlobConfig;
|
||||||
|
}): Promise<Blob> => {
|
||||||
const max = Math.max(width, height);
|
let { mimeType = MIME_TYPES.png, quality } = config || {};
|
||||||
|
|
||||||
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 ?? 1,
|
|
||||||
};
|
|
||||||
},
|
|
||||||
);
|
|
||||||
};
|
|
||||||
|
|
||||||
export const exportToBlob = async (
|
|
||||||
opts: ExportOpts & {
|
|
||||||
mimeType?: string;
|
|
||||||
quality?: number;
|
|
||||||
exportPadding?: number;
|
|
||||||
},
|
|
||||||
): Promise<Blob> => {
|
|
||||||
let { mimeType = MIME_TYPES.png, quality } = opts;
|
|
||||||
|
|
||||||
if (mimeType === MIME_TYPES.png && typeof quality === "number") {
|
if (mimeType === MIME_TYPES.png && typeof quality === "number") {
|
||||||
console.warn(`"quality" will be ignored for "${MIME_TYPES.png}" mimeType`);
|
console.warn(`"quality" will be ignored for "${MIME_TYPES.png}" mimeType`);
|
||||||
@ -104,17 +46,21 @@ export const exportToBlob = async (
|
|||||||
mimeType = MIME_TYPES.jpg;
|
mimeType = MIME_TYPES.jpg;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (mimeType === MIME_TYPES.jpg && !opts.appState?.exportBackground) {
|
if (mimeType === MIME_TYPES.jpg && !config?.canvasBackgroundColor === false) {
|
||||||
console.warn(
|
console.warn(
|
||||||
`Defaulting "exportBackground" to "true" for "${MIME_TYPES.jpg}" mimeType`,
|
`Defaulting "exportBackground" to "true" for "${MIME_TYPES.jpg}" mimeType`,
|
||||||
);
|
);
|
||||||
opts = {
|
config = {
|
||||||
...opts,
|
...config,
|
||||||
appState: { ...opts.appState, exportBackground: true },
|
canvasBackgroundColor:
|
||||||
|
data.appState?.viewBackgroundColor || DEFAULT_BACKGROUND_COLOR,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const canvas = await exportToCanvas(opts);
|
const canvas = await exportToCanvas({
|
||||||
|
data,
|
||||||
|
config,
|
||||||
|
});
|
||||||
|
|
||||||
quality = quality ? quality : /image\/jpe?g/.test(mimeType) ? 0.92 : 0.8;
|
quality = quality ? quality : /image\/jpe?g/.test(mimeType) ? 0.92 : 0.8;
|
||||||
|
|
||||||
@ -127,14 +73,14 @@ export const exportToBlob = async (
|
|||||||
if (
|
if (
|
||||||
blob &&
|
blob &&
|
||||||
mimeType === MIME_TYPES.png &&
|
mimeType === MIME_TYPES.png &&
|
||||||
opts.appState?.exportEmbedScene
|
data.appState?.exportEmbedScene
|
||||||
) {
|
) {
|
||||||
blob = await encodePngMetadata({
|
blob = await encodePngMetadata({
|
||||||
blob,
|
blob,
|
||||||
metadata: serializeAsJSON(
|
metadata: serializeAsJSON(
|
||||||
opts.elements,
|
data.elements,
|
||||||
opts.appState,
|
data.appState,
|
||||||
opts.files || {},
|
data.files || {},
|
||||||
"local",
|
"local",
|
||||||
),
|
),
|
||||||
});
|
});
|
||||||
@ -148,50 +94,50 @@ export const exportToBlob = async (
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const exportToSvg = async ({
|
export const exportToSvg = async ({
|
||||||
elements,
|
data,
|
||||||
appState = getDefaultAppState(),
|
config,
|
||||||
files = {},
|
}: {
|
||||||
exportPadding,
|
data: ExportToCanvasData;
|
||||||
}: Omit<ExportOpts, "getDimensions"> & {
|
config?: ExportToSvgConfig;
|
||||||
exportPadding?: number;
|
|
||||||
}): Promise<SVGSVGElement> => {
|
}): Promise<SVGSVGElement> => {
|
||||||
const { elements: restoredElements, appState: restoredAppState } = restore(
|
const { elements: restoredElements, appState: restoredAppState } = restore(
|
||||||
{ elements, appState },
|
{ ...data, files: data.files || {} },
|
||||||
null,
|
null,
|
||||||
null,
|
null,
|
||||||
);
|
);
|
||||||
return _exportToSvg(
|
return _exportToSvg(
|
||||||
getNonDeletedElements(restoredElements),
|
getNonDeletedElements(restoredElements),
|
||||||
{
|
{ ...restoredAppState, exportPadding: config?.padding },
|
||||||
...restoredAppState,
|
data.files || {},
|
||||||
exportPadding,
|
|
||||||
},
|
|
||||||
files,
|
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const exportToClipboard = async (
|
export const exportToClipboard = async ({
|
||||||
opts: ExportOpts & {
|
type,
|
||||||
mimeType?: string;
|
data,
|
||||||
quality?: number;
|
config,
|
||||||
type: "png" | "svg" | "json";
|
}: {
|
||||||
},
|
data: ExportToCanvasData;
|
||||||
) => {
|
} & (
|
||||||
if (opts.type === "svg") {
|
| { type: "png"; config?: ExportToBlobConfig }
|
||||||
const svg = await exportToSvg(opts);
|
| { type: "svg"; config?: ExportToSvgConfig }
|
||||||
|
| { type: "json"; config?: never }
|
||||||
|
)) => {
|
||||||
|
if (type === "svg") {
|
||||||
|
const svg = await exportToSvg({ data, config });
|
||||||
await copyTextToSystemClipboard(svg.outerHTML);
|
await copyTextToSystemClipboard(svg.outerHTML);
|
||||||
} else if (opts.type === "png") {
|
} else if (type === "png") {
|
||||||
await copyBlobToClipboardAsPng(exportToBlob(opts));
|
await copyBlobToClipboardAsPng(exportToBlob({ data, config }));
|
||||||
} else if (opts.type === "json") {
|
} else if (type === "json") {
|
||||||
const appState = {
|
const appState = {
|
||||||
offsetTop: 0,
|
offsetTop: 0,
|
||||||
offsetLeft: 0,
|
offsetLeft: 0,
|
||||||
width: 0,
|
width: 0,
|
||||||
height: 0,
|
height: 0,
|
||||||
...getDefaultAppState(),
|
...getDefaultAppState(),
|
||||||
...opts.appState,
|
...data.appState,
|
||||||
};
|
};
|
||||||
await copyToClipboard(opts.elements, appState, opts.files);
|
await copyToClipboard(data.elements, appState, data.files);
|
||||||
} else {
|
} else {
|
||||||
throw new Error("Invalid export type");
|
throw new Error("Invalid export type");
|
||||||
}
|
}
|
||||||
|
@ -317,14 +317,12 @@ const renderLinearElementPointHighlight = (
|
|||||||
export const _renderScene = ({
|
export const _renderScene = ({
|
||||||
elements,
|
elements,
|
||||||
appState,
|
appState,
|
||||||
scale,
|
|
||||||
rc,
|
rc,
|
||||||
canvas,
|
canvas,
|
||||||
renderConfig,
|
renderConfig,
|
||||||
}: {
|
}: {
|
||||||
elements: readonly NonDeletedExcalidrawElement[];
|
elements: readonly NonDeletedExcalidrawElement[];
|
||||||
appState: AppState;
|
appState: AppState;
|
||||||
scale: number;
|
|
||||||
rc: RoughCanvas;
|
rc: RoughCanvas;
|
||||||
canvas: HTMLCanvasElement;
|
canvas: HTMLCanvasElement;
|
||||||
renderConfig: RenderConfig;
|
renderConfig: RenderConfig;
|
||||||
@ -347,27 +345,27 @@ export const _renderScene = ({
|
|||||||
|
|
||||||
context.setTransform(1, 0, 0, 1, 0, 0);
|
context.setTransform(1, 0, 0, 1, 0, 0);
|
||||||
context.save();
|
context.save();
|
||||||
context.scale(scale, scale);
|
context.scale(renderConfig.canvasScale, renderConfig.canvasScale);
|
||||||
// When doing calculations based on canvas width we should used normalized one
|
// When doing calculations based on canvas width we should used normalized one
|
||||||
const normalizedCanvasWidth = canvas.width / scale;
|
const normalizedCanvasWidth = canvas.width / renderConfig.canvasScale;
|
||||||
const normalizedCanvasHeight = canvas.height / scale;
|
const normalizedCanvasHeight = canvas.height / renderConfig.canvasScale;
|
||||||
|
|
||||||
if (isExporting && renderConfig.theme === "dark") {
|
if (isExporting && renderConfig.theme === "dark") {
|
||||||
context.filter = THEME_FILTER;
|
context.filter = THEME_FILTER;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Paint background
|
// Paint background
|
||||||
if (typeof renderConfig.viewBackgroundColor === "string") {
|
if (typeof renderConfig.canvasBackgroundColor === "string") {
|
||||||
const hasTransparence =
|
const hasTransparence =
|
||||||
renderConfig.viewBackgroundColor === "transparent" ||
|
renderConfig.canvasBackgroundColor === "transparent" ||
|
||||||
renderConfig.viewBackgroundColor.length === 5 || // #RGBA
|
renderConfig.canvasBackgroundColor.length === 5 || // #RGBA
|
||||||
renderConfig.viewBackgroundColor.length === 9 || // #RRGGBBA
|
renderConfig.canvasBackgroundColor.length === 9 || // #RRGGBBA
|
||||||
/(hsla|rgba)\(/.test(renderConfig.viewBackgroundColor);
|
/(hsla|rgba)\(/.test(renderConfig.canvasBackgroundColor);
|
||||||
if (hasTransparence) {
|
if (hasTransparence) {
|
||||||
context.clearRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
|
context.clearRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
|
||||||
}
|
}
|
||||||
context.save();
|
context.save();
|
||||||
context.fillStyle = renderConfig.viewBackgroundColor;
|
context.fillStyle = renderConfig.canvasBackgroundColor;
|
||||||
context.fillRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
|
context.fillRect(0, 0, normalizedCanvasWidth, normalizedCanvasHeight);
|
||||||
context.restore();
|
context.restore();
|
||||||
} else {
|
} else {
|
||||||
@ -796,7 +794,6 @@ const renderSceneThrottled = throttleRAF(
|
|||||||
(config: {
|
(config: {
|
||||||
elements: readonly NonDeletedExcalidrawElement[];
|
elements: readonly NonDeletedExcalidrawElement[];
|
||||||
appState: AppState;
|
appState: AppState;
|
||||||
scale: number;
|
|
||||||
rc: RoughCanvas;
|
rc: RoughCanvas;
|
||||||
canvas: HTMLCanvasElement;
|
canvas: HTMLCanvasElement;
|
||||||
renderConfig: RenderConfig;
|
renderConfig: RenderConfig;
|
||||||
@ -813,7 +810,6 @@ export const renderScene = <T extends boolean = false>(
|
|||||||
config: {
|
config: {
|
||||||
elements: readonly NonDeletedExcalidrawElement[];
|
elements: readonly NonDeletedExcalidrawElement[];
|
||||||
appState: AppState;
|
appState: AppState;
|
||||||
scale: number;
|
|
||||||
rc: RoughCanvas;
|
rc: RoughCanvas;
|
||||||
canvas: HTMLCanvasElement;
|
canvas: HTMLCanvasElement;
|
||||||
renderConfig: RenderConfig;
|
renderConfig: RenderConfig;
|
||||||
|
@ -1,73 +1,309 @@
|
|||||||
import rough from "roughjs/bin/rough";
|
import rough from "roughjs/bin/rough";
|
||||||
import { NonDeletedExcalidrawElement } from "../element/types";
|
import { NonDeletedExcalidrawElement, Theme } from "../element/types";
|
||||||
import { getCommonBounds } from "../element/bounds";
|
import { getCommonBounds } from "../element/bounds";
|
||||||
import { renderScene, renderSceneToSvg } from "../renderer/renderScene";
|
import { renderScene, renderSceneToSvg } from "../renderer/renderScene";
|
||||||
import { distance } from "../utils";
|
import { distance } from "../utils";
|
||||||
import { AppState, BinaryFiles } from "../types";
|
import { AppState, BinaryFiles } from "../types";
|
||||||
import { DEFAULT_EXPORT_PADDING, SVG_NS, THEME_FILTER } from "../constants";
|
import {
|
||||||
import { getDefaultAppState } from "../appState";
|
DEFAULT_BACKGROUND_COLOR,
|
||||||
|
DEFAULT_EXPORT_PADDING,
|
||||||
|
DEFAULT_ZOOM_VALUE,
|
||||||
|
ENV,
|
||||||
|
SVG_NS,
|
||||||
|
THEME,
|
||||||
|
THEME_FILTER,
|
||||||
|
} from "../constants";
|
||||||
import { serializeAsJSON } from "../data/json";
|
import { serializeAsJSON } from "../data/json";
|
||||||
import {
|
import {
|
||||||
getInitializedImageElements,
|
getInitializedImageElements,
|
||||||
updateImageCache,
|
updateImageCache,
|
||||||
} from "../element/image";
|
} from "../element/image";
|
||||||
|
import { restoreAppState } from "../data/restore";
|
||||||
|
|
||||||
export const SVG_EXPORT_TAG = `<!-- svg-source:excalidraw -->`;
|
export const SVG_EXPORT_TAG = `<!-- svg-source:excalidraw -->`;
|
||||||
|
|
||||||
export const exportToCanvas = async (
|
export type ExportToCanvasData = {
|
||||||
elements: readonly NonDeletedExcalidrawElement[],
|
elements: readonly NonDeletedExcalidrawElement[];
|
||||||
appState: AppState,
|
appState?: Partial<Omit<AppState, "offsetTop" | "offsetLeft">>;
|
||||||
files: BinaryFiles,
|
files: BinaryFiles | null;
|
||||||
{
|
};
|
||||||
exportBackground,
|
|
||||||
exportPadding = DEFAULT_EXPORT_PADDING,
|
export type ExportToCanvasConfig = {
|
||||||
viewBackgroundColor,
|
theme?: Theme;
|
||||||
}: {
|
/**
|
||||||
exportBackground: boolean;
|
* Canvas background. Valid values are:
|
||||||
exportPadding?: number;
|
*
|
||||||
viewBackgroundColor: string;
|
* - `undefined` - the background of "appState.viewBackgroundColor" is used.
|
||||||
},
|
* - `false` - no background is used (set to "transparent").
|
||||||
createCanvas: (
|
* - `string` - should be a valid CSS color.
|
||||||
|
*
|
||||||
|
* @default undefined
|
||||||
|
*/
|
||||||
|
canvasBackgroundColor?: string | false;
|
||||||
|
/**
|
||||||
|
* Canvas padding in pixels. Affected by scale. Ignored if `fit` is set to
|
||||||
|
* `cover`.
|
||||||
|
*
|
||||||
|
* @default 10
|
||||||
|
*/
|
||||||
|
padding?: number;
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
/**
|
||||||
|
* Makes sure the canvas is no larger than this value, while keeping the
|
||||||
|
* aspect ratio.
|
||||||
|
*
|
||||||
|
* Technically can get smaller/larger if used in conjunction with
|
||||||
|
* `scale`.
|
||||||
|
*/
|
||||||
|
maxWidthOrHeight?: number;
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
/**
|
||||||
|
* Width of the frame. Supply `x` or `y` if you want to ofsset the canvas.
|
||||||
|
*
|
||||||
|
* Defaults to the content bounding box width.
|
||||||
|
*/
|
||||||
|
width?: number;
|
||||||
|
/**
|
||||||
|
* Height of the frame.
|
||||||
|
*
|
||||||
|
* If height omitted, the height is calculated from the the content's
|
||||||
|
* bounding box to preserve the aspect ratio.
|
||||||
|
*
|
||||||
|
* Defaults to the content bounding box height.
|
||||||
|
*/
|
||||||
|
height?: number;
|
||||||
|
/**
|
||||||
|
* Left canvas position. Defaults to the `x` postion of the content bounding
|
||||||
|
* box.
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
x?: number;
|
||||||
|
/**
|
||||||
|
* Top canvas position.
|
||||||
|
*
|
||||||
|
* 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, 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.
|
||||||
|
* - `cover` - scale to fill the frame while maintaining aspect ratio. If
|
||||||
|
* content overflows, it will be cropped.
|
||||||
|
*
|
||||||
|
* @default "contain" unless `x` or `y` are specified, in which case "none"
|
||||||
|
* is used (forced).
|
||||||
|
*/
|
||||||
|
fit?: "none" | "contain" | "cover";
|
||||||
|
/**
|
||||||
|
* If `fit` is set to `none` or `cover`, and neither `x` or `y` are
|
||||||
|
* specified, indicates how the canvas should be aligned.
|
||||||
|
*
|
||||||
|
* - `none` - canvas aligned to top left.
|
||||||
|
* - `center` - canvas is centered. Aligned to either axis (or both) that's
|
||||||
|
* not specified.
|
||||||
|
*
|
||||||
|
* @default "center"
|
||||||
|
*/
|
||||||
|
position?: "center" | "none";
|
||||||
|
// -------------------------------------------------------------------------
|
||||||
|
/**
|
||||||
|
* A multiplier to increase/decrease the canvas resolution.
|
||||||
|
*
|
||||||
|
* For example, if your canvas is 300x150 and you set scale to 2, the
|
||||||
|
* resoluting size will be 600x300.
|
||||||
|
*
|
||||||
|
* @default 1
|
||||||
|
*/
|
||||||
|
scale?: number;
|
||||||
|
/**
|
||||||
|
* If you need to suply your own canvas, e.g. in test environments or on
|
||||||
|
* Node.js.
|
||||||
|
*
|
||||||
|
* Do not set canvas.width/height or modify the 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` or `width` is set.
|
||||||
|
*/
|
||||||
|
getDimensions?: (
|
||||||
width: number,
|
width: number,
|
||||||
height: number,
|
height: number,
|
||||||
) => { canvas: HTMLCanvasElement; scale: number } = (width, height) => {
|
) => { width: number; height: number; scale?: number };
|
||||||
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);
|
|
||||||
|
|
||||||
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);
|
||||||
|
|
||||||
|
if (cfg.x != null || cfg.x != null) {
|
||||||
|
if (cfg.fit != null && cfg.fit !== "none") {
|
||||||
|
if (process.env.NODE_ENV === ENV.DEVELOPMENT) {
|
||||||
|
console.warn(
|
||||||
|
"`fit` will be ignored (automatically set to `none`) when you specify `x` or `y` offsets",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
cfg.fit = "none";
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg.fit = cfg.fit ?? "contain";
|
||||||
|
|
||||||
|
if (cfg.fit === "cover" && cfg.padding) {
|
||||||
|
if (process.env.NODE_ENV === ENV.DEVELOPMENT) {
|
||||||
|
console.warn("`padding` is ignored when `fit` is set to `cover`");
|
||||||
|
}
|
||||||
|
cfg.padding = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
cfg.scale = cfg.scale ?? 1;
|
||||||
|
|
||||||
|
cfg.origin = cfg.origin ?? "canvas";
|
||||||
|
cfg.position = cfg.position ?? "center";
|
||||||
|
cfg.padding = cfg.padding ?? DEFAULT_EXPORT_PADDING;
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
let canvasScale = 1;
|
||||||
|
|
||||||
|
const canvasSize = getCanvasSize(elements, cfg.padding);
|
||||||
|
const [contentX, contentY, contentWidth, contentHeight] = canvasSize;
|
||||||
|
let [x, y, width, height] = canvasSize;
|
||||||
|
|
||||||
|
if (cfg.maxWidthOrHeight != null) {
|
||||||
|
canvasScale = cfg.maxWidthOrHeight / Math.max(contentWidth, contentHeight);
|
||||||
|
|
||||||
|
width *= canvasScale;
|
||||||
|
height *= canvasScale;
|
||||||
|
} else if (cfg.width != null) {
|
||||||
|
width = cfg.width;
|
||||||
|
|
||||||
|
if (cfg.height) {
|
||||||
|
height = cfg.height;
|
||||||
|
} else {
|
||||||
|
height *= width / contentWidth;
|
||||||
|
}
|
||||||
|
} else if (cfg.height != null) {
|
||||||
|
height = cfg.height;
|
||||||
|
width *= height / contentHeight;
|
||||||
|
} else if (cfg.getDimensions) {
|
||||||
|
const ret = cfg.getDimensions(width, height);
|
||||||
|
|
||||||
|
width = ret.width;
|
||||||
|
height = ret.height;
|
||||||
|
cfg.scale = ret.scale ?? cfg.scale;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cfg.fit === "contain" && !cfg.maxWidthOrHeight) {
|
||||||
|
const oRatio = contentWidth / contentHeight;
|
||||||
|
const cRatio = width / height;
|
||||||
|
|
||||||
|
if (oRatio > cRatio) {
|
||||||
|
canvasScale = width / contentWidth;
|
||||||
|
} else {
|
||||||
|
canvasScale = height / contentHeight;
|
||||||
|
}
|
||||||
|
} else if (cfg.fit === "cover") {
|
||||||
|
const wRatio = width / contentWidth;
|
||||||
|
const hRatio = height / contentHeight;
|
||||||
|
canvasScale = wRatio > hRatio ? wRatio : hRatio;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (cfg.origin === "content") {
|
||||||
|
if (cfg.x != null) {
|
||||||
|
cfg.x = cfg.x + contentX;
|
||||||
|
}
|
||||||
|
if (cfg.y != null) {
|
||||||
|
cfg.y = cfg.y + contentY;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
x = cfg.x ?? contentX;
|
||||||
|
y = cfg.y ?? contentY;
|
||||||
|
|
||||||
|
if (cfg.position === "center") {
|
||||||
|
if (cfg.x == null) {
|
||||||
|
x -= width / canvasScale / 2 - contentWidth / 2;
|
||||||
|
}
|
||||||
|
if (cfg.y == null) {
|
||||||
|
y -= height / canvasScale / 2 - contentHeight / 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const canvas = cfg.createCanvas
|
||||||
|
? cfg.createCanvas()
|
||||||
|
: document.createElement("canvas");
|
||||||
|
|
||||||
|
canvasScale *= cfg.scale;
|
||||||
|
width *= cfg.scale;
|
||||||
|
height *= cfg.scale;
|
||||||
|
|
||||||
|
canvas.width = width;
|
||||||
|
canvas.height = height;
|
||||||
|
|
||||||
const { imageCache } = await updateImageCache({
|
const { imageCache } = await updateImageCache({
|
||||||
imageCache: new Map(),
|
imageCache: new Map(),
|
||||||
fileIds: getInitializedImageElements(elements).map(
|
fileIds: getInitializedImageElements(elements).map(
|
||||||
(element) => element.fileId,
|
(element) => element.fileId,
|
||||||
),
|
),
|
||||||
files,
|
files: files || {},
|
||||||
});
|
});
|
||||||
|
|
||||||
renderScene({
|
renderScene({
|
||||||
elements,
|
elements,
|
||||||
appState,
|
appState: { ...appState, width, height, offsetLeft: 0, offsetTop: 0 },
|
||||||
scale,
|
|
||||||
rc: rough.canvas(canvas),
|
rc: rough.canvas(canvas),
|
||||||
canvas,
|
canvas,
|
||||||
renderConfig: {
|
renderConfig: {
|
||||||
viewBackgroundColor: exportBackground ? viewBackgroundColor : null,
|
canvasBackgroundColor:
|
||||||
scrollX: -minX + exportPadding,
|
cfg.canvasBackgroundColor === false
|
||||||
scrollY: -minY + exportPadding,
|
? // null indicates transparent background
|
||||||
zoom: defaultAppState.zoom,
|
null
|
||||||
|
: cfg.canvasBackgroundColor ||
|
||||||
|
appState.viewBackgroundColor ||
|
||||||
|
DEFAULT_BACKGROUND_COLOR,
|
||||||
|
scrollX: -x + cfg.padding,
|
||||||
|
scrollY: -y + cfg.padding,
|
||||||
|
canvasScale,
|
||||||
|
zoom: { value: DEFAULT_ZOOM_VALUE },
|
||||||
remotePointerViewportCoords: {},
|
remotePointerViewportCoords: {},
|
||||||
remoteSelectedElementIds: {},
|
remoteSelectedElementIds: {},
|
||||||
shouldCacheIgnoreZoom: false,
|
shouldCacheIgnoreZoom: false,
|
||||||
remotePointerUsernames: {},
|
remotePointerUsernames: {},
|
||||||
remotePointerUserStates: {},
|
remotePointerUserStates: {},
|
||||||
theme: appState.exportWithDarkMode ? "dark" : "light",
|
theme: cfg.theme || THEME.LIGHT,
|
||||||
imageCache,
|
imageCache,
|
||||||
renderScrollbars: false,
|
renderScrollbars: false,
|
||||||
renderSelection: false,
|
renderSelection: false,
|
||||||
@ -176,7 +412,7 @@ export const exportToSvg = async (
|
|||||||
const getCanvasSize = (
|
const getCanvasSize = (
|
||||||
elements: readonly NonDeletedExcalidrawElement[],
|
elements: readonly NonDeletedExcalidrawElement[],
|
||||||
exportPadding: number,
|
exportPadding: number,
|
||||||
): [number, number, number, number] => {
|
): [minX: number, minY: number, width: number, height: number] => {
|
||||||
const [minX, minY, maxX, maxY] = getCommonBounds(elements);
|
const [minX, minY, maxX, maxY] = getCommonBounds(elements);
|
||||||
const width = distance(minX, maxX) + exportPadding * 2;
|
const width = distance(minX, maxX) + exportPadding * 2;
|
||||||
const height = distance(minY, maxY) + exportPadding + exportPadding;
|
const height = distance(minY, maxY) + exportPadding + exportPadding;
|
||||||
@ -186,10 +422,10 @@ const getCanvasSize = (
|
|||||||
|
|
||||||
export const getExportSize = (
|
export const getExportSize = (
|
||||||
elements: readonly NonDeletedExcalidrawElement[],
|
elements: readonly NonDeletedExcalidrawElement[],
|
||||||
exportPadding: number,
|
padding: number,
|
||||||
scale: number,
|
scale: number,
|
||||||
): [number, number] => {
|
): [number, number] => {
|
||||||
const [, , width, height] = getCanvasSize(elements, exportPadding).map(
|
const [, , width, height] = getCanvasSize(elements, padding).map(
|
||||||
(dimension) => Math.trunc(dimension * scale),
|
(dimension) => Math.trunc(dimension * scale),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
@ -2,15 +2,23 @@ import { ExcalidrawTextElement } from "../element/types";
|
|||||||
import { AppClassProperties, AppState } from "../types";
|
import { AppClassProperties, AppState } from "../types";
|
||||||
|
|
||||||
export type RenderConfig = {
|
export type RenderConfig = {
|
||||||
// AppState values
|
// canvas related (AppState)
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
scrollX: AppState["scrollX"];
|
scrollX: AppState["scrollX"];
|
||||||
scrollY: AppState["scrollY"];
|
scrollY: AppState["scrollY"];
|
||||||
/** null indicates transparent bg */
|
/** null indicates transparent bg */
|
||||||
viewBackgroundColor: AppState["viewBackgroundColor"] | null;
|
canvasBackgroundColor: AppState["viewBackgroundColor"] | null;
|
||||||
zoom: AppState["zoom"];
|
zoom: AppState["zoom"];
|
||||||
shouldCacheIgnoreZoom: AppState["shouldCacheIgnoreZoom"];
|
shouldCacheIgnoreZoom: AppState["shouldCacheIgnoreZoom"];
|
||||||
theme: AppState["theme"];
|
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
|
// collab-related state
|
||||||
// ---------------------------------------------------------------------------
|
// ---------------------------------------------------------------------------
|
||||||
remotePointerViewportCoords: { [id: string]: { x: number; y: number } };
|
remotePointerViewportCoords: { [id: string]: { x: number; y: number } };
|
||||||
|
@ -3,6 +3,7 @@ import { diagramFactory } from "../fixtures/diagramFixture";
|
|||||||
import * as mockedSceneExportUtils from "../../scene/export";
|
import * as mockedSceneExportUtils from "../../scene/export";
|
||||||
import { MIME_TYPES } from "../../constants";
|
import { MIME_TYPES } from "../../constants";
|
||||||
|
|
||||||
|
import { exportToCanvas } from "../../scene/export";
|
||||||
jest.mock("../../scene/export", () => ({
|
jest.mock("../../scene/export", () => ({
|
||||||
__esmodule: true,
|
__esmodule: true,
|
||||||
...jest.requireActual("../../scene/export"),
|
...jest.requireActual("../../scene/export"),
|
||||||
@ -13,8 +14,8 @@ describe("exportToCanvas", () => {
|
|||||||
const EXPORT_PADDING = 10;
|
const EXPORT_PADDING = 10;
|
||||||
|
|
||||||
it("with default arguments", async () => {
|
it("with default arguments", async () => {
|
||||||
const canvas = await utils.exportToCanvas({
|
const canvas = await exportToCanvas({
|
||||||
...diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
|
data: diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(canvas.width).toBe(100 + 2 * EXPORT_PADDING);
|
expect(canvas.width).toBe(100 + 2 * EXPORT_PADDING);
|
||||||
@ -22,9 +23,13 @@ describe("exportToCanvas", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
it("when custom width and height", async () => {
|
it("when custom width and height", async () => {
|
||||||
const canvas = await utils.exportToCanvas({
|
const canvas = await exportToCanvas({
|
||||||
...diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
|
data: {
|
||||||
getDimensions: () => ({ width: 200, height: 200, scale: 1 }),
|
...diagramFactory({ elementOverrides: { width: 100, height: 100 } }),
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
getDimensions: () => ({ width: 200, height: 200, scale: 1 }),
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(canvas.width).toBe(200);
|
expect(canvas.width).toBe(200);
|
||||||
@ -38,12 +43,17 @@ describe("exportToBlob", () => {
|
|||||||
|
|
||||||
it("should change image/jpg to image/jpeg", async () => {
|
it("should change image/jpg to image/jpeg", async () => {
|
||||||
const blob = await utils.exportToBlob({
|
const blob = await utils.exportToBlob({
|
||||||
...diagramFactory(),
|
data: {
|
||||||
getDimensions: (width, height) => ({ width, height, scale: 1 }),
|
...diagramFactory(),
|
||||||
// testing typo in MIME type (jpg → jpeg)
|
|
||||||
mimeType: "image/jpg",
|
appState: {
|
||||||
appState: {
|
exportBackground: true,
|
||||||
exportBackground: true,
|
},
|
||||||
|
},
|
||||||
|
config: {
|
||||||
|
getDimensions: (width, height) => ({ width, height, scale: 1 }),
|
||||||
|
// testing typo in MIME type (jpg → jpeg)
|
||||||
|
mimeType: "image/jpg",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
expect(blob?.type).toBe(MIME_TYPES.jpg);
|
expect(blob?.type).toBe(MIME_TYPES.jpg);
|
||||||
@ -51,7 +61,7 @@ describe("exportToBlob", () => {
|
|||||||
|
|
||||||
it("should default to image/png", async () => {
|
it("should default to image/png", async () => {
|
||||||
const blob = await utils.exportToBlob({
|
const blob = await utils.exportToBlob({
|
||||||
...diagramFactory(),
|
data: diagramFactory(),
|
||||||
});
|
});
|
||||||
expect(blob?.type).toBe(MIME_TYPES.png);
|
expect(blob?.type).toBe(MIME_TYPES.png);
|
||||||
});
|
});
|
||||||
@ -62,9 +72,11 @@ describe("exportToBlob", () => {
|
|||||||
.mockImplementationOnce(() => void 0);
|
.mockImplementationOnce(() => void 0);
|
||||||
|
|
||||||
await utils.exportToBlob({
|
await utils.exportToBlob({
|
||||||
...diagramFactory(),
|
data: diagramFactory(),
|
||||||
mimeType: MIME_TYPES.png,
|
config: {
|
||||||
quality: 1,
|
mimeType: MIME_TYPES.png,
|
||||||
|
quality: 1,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(consoleSpy).toHaveBeenCalledWith(
|
expect(consoleSpy).toHaveBeenCalledWith(
|
||||||
@ -82,7 +94,7 @@ describe("exportToSvg", () => {
|
|||||||
|
|
||||||
it("with default arguments", async () => {
|
it("with default arguments", async () => {
|
||||||
await utils.exportToSvg({
|
await utils.exportToSvg({
|
||||||
...diagramFactory({
|
data: diagramFactory({
|
||||||
overrides: { appState: void 0 },
|
overrides: { appState: void 0 },
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
@ -98,7 +110,7 @@ describe("exportToSvg", () => {
|
|||||||
|
|
||||||
it("with deleted elements", async () => {
|
it("with deleted elements", async () => {
|
||||||
await utils.exportToSvg({
|
await utils.exportToSvg({
|
||||||
...diagramFactory({
|
data: diagramFactory({
|
||||||
overrides: { appState: void 0 },
|
overrides: { appState: void 0 },
|
||||||
elementOverrides: { isDeleted: true },
|
elementOverrides: { isDeleted: true },
|
||||||
}),
|
}),
|
||||||
@ -109,8 +121,10 @@ describe("exportToSvg", () => {
|
|||||||
|
|
||||||
it("with exportPadding", async () => {
|
it("with exportPadding", async () => {
|
||||||
await utils.exportToSvg({
|
await utils.exportToSvg({
|
||||||
...diagramFactory({ overrides: { appState: { name: "diagram name" } } }),
|
data: diagramFactory({
|
||||||
exportPadding: 0,
|
overrides: { appState: { name: "diagram name" } },
|
||||||
|
}),
|
||||||
|
config: { padding: 0 },
|
||||||
});
|
});
|
||||||
|
|
||||||
expect(passedElements().length).toBe(3);
|
expect(passedElements().length).toBe(3);
|
||||||
@ -121,7 +135,7 @@ describe("exportToSvg", () => {
|
|||||||
|
|
||||||
it("with exportEmbedScene", async () => {
|
it("with exportEmbedScene", async () => {
|
||||||
await utils.exportToSvg({
|
await utils.exportToSvg({
|
||||||
...diagramFactory({
|
data: diagramFactory({
|
||||||
overrides: {
|
overrides: {
|
||||||
appState: { name: "diagram name", exportEmbedScene: true },
|
appState: { name: "diagram name", exportEmbedScene: true },
|
||||||
},
|
},
|
||||||
|
Loading…
x
Reference in New Issue
Block a user