utils.ts 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import {
  2. exportToCanvas as _exportToCanvas,
  3. exportToSvg as _exportToSvg,
  4. } from "../scene/export";
  5. import { getDefaultAppState } from "../appState";
  6. import { AppState } from "../types";
  7. import { ExcalidrawElement } from "../element/types";
  8. import { getNonDeletedElements } from "../element";
  9. type ExportOpts = {
  10. elements: readonly ExcalidrawElement[];
  11. appState?: Omit<AppState, "offsetTop" | "offsetLeft">;
  12. getDimensions: (
  13. width: number,
  14. height: number,
  15. ) => { width: number; height: number; scale: number };
  16. };
  17. export const exportToCanvas = ({
  18. elements,
  19. appState = getDefaultAppState(),
  20. getDimensions = (width, height) => ({ width, height, scale: 1 }),
  21. }: ExportOpts) => {
  22. return _exportToCanvas(
  23. getNonDeletedElements(elements),
  24. { ...appState, offsetTop: 0, offsetLeft: 0 },
  25. {
  26. exportBackground: appState.exportBackground ?? true,
  27. viewBackgroundColor: appState.viewBackgroundColor ?? "#FFF",
  28. shouldAddWatermark: appState.shouldAddWatermark ?? false,
  29. },
  30. (width: number, height: number) => {
  31. const canvas = document.createElement("canvas");
  32. const ret = getDimensions(width, height);
  33. canvas.width = ret.width;
  34. canvas.height = ret.height;
  35. return { canvas, scale: ret.scale };
  36. },
  37. );
  38. };
  39. export const exportToBlob = (
  40. opts: ExportOpts & {
  41. mimeType?: string;
  42. quality?: number;
  43. },
  44. ): Promise<Blob | null> => {
  45. const canvas = exportToCanvas(opts);
  46. let { mimeType = "image/png", quality } = opts;
  47. if (mimeType === "image/png" && typeof quality === "number") {
  48. console.warn(`"quality" will be ignored for "image/png" mimeType`);
  49. }
  50. if (mimeType === "image/jpg") {
  51. mimeType = "image/jpeg";
  52. }
  53. quality = quality ? quality : /image\/jpe?g/.test(mimeType) ? 0.92 : 0.8;
  54. return new Promise((resolve) => {
  55. canvas.toBlob(
  56. (blob: Blob | null) => {
  57. resolve(blob);
  58. },
  59. mimeType,
  60. quality,
  61. );
  62. });
  63. };
  64. export const exportToSvg = ({
  65. elements,
  66. appState = getDefaultAppState(),
  67. exportPadding,
  68. metadata,
  69. }: ExportOpts & {
  70. exportPadding?: number;
  71. metadata?: string;
  72. }): SVGSVGElement => {
  73. return _exportToSvg(getNonDeletedElements(elements), {
  74. ...appState,
  75. exportPadding,
  76. metadata,
  77. });
  78. };