getExportCanvasPreview.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. import rough from "roughjs/bin/rough";
  2. import { ExcalidrawElement } from "../element/types";
  3. import { getElementAbsoluteCoords } from "../element/bounds";
  4. import { renderScene } from "../renderer/renderScene";
  5. export function getExportCanvasPreview(
  6. elements: readonly ExcalidrawElement[],
  7. {
  8. exportBackground,
  9. exportPadding = 10,
  10. viewBackgroundColor,
  11. scale = 1
  12. }: {
  13. exportBackground: boolean;
  14. exportPadding?: number;
  15. scale?: number;
  16. viewBackgroundColor: string;
  17. },
  18. createCanvas: (width: number, height: number) => any = function(
  19. width,
  20. height
  21. ) {
  22. const tempCanvas = document.createElement("canvas");
  23. tempCanvas.style.width = width + "px";
  24. tempCanvas.style.height = height + "px";
  25. tempCanvas.width = width * scale;
  26. tempCanvas.height = height * scale;
  27. return tempCanvas;
  28. }
  29. ) {
  30. // calculate smallest area to fit the contents in
  31. let subCanvasX1 = Infinity;
  32. let subCanvasX2 = 0;
  33. let subCanvasY1 = Infinity;
  34. let subCanvasY2 = 0;
  35. elements.forEach(element => {
  36. const [x1, y1, x2, y2] = getElementAbsoluteCoords(element);
  37. subCanvasX1 = Math.min(subCanvasX1, x1);
  38. subCanvasY1 = Math.min(subCanvasY1, y1);
  39. subCanvasX2 = Math.max(subCanvasX2, x2);
  40. subCanvasY2 = Math.max(subCanvasY2, y2);
  41. });
  42. function distance(x: number, y: number) {
  43. return Math.abs(x > y ? x - y : y - x);
  44. }
  45. const width = distance(subCanvasX1, subCanvasX2) + exportPadding * 2;
  46. const height = distance(subCanvasY1, subCanvasY2) + exportPadding * 2;
  47. const tempCanvas: any = createCanvas(width, height);
  48. tempCanvas.getContext("2d")?.scale(scale, scale);
  49. renderScene(
  50. elements,
  51. rough.canvas(tempCanvas),
  52. tempCanvas,
  53. {
  54. viewBackgroundColor: exportBackground ? viewBackgroundColor : null,
  55. scrollX: 0,
  56. scrollY: 0
  57. },
  58. {
  59. offsetX: -subCanvasX1 + exportPadding,
  60. offsetY: -subCanvasY1 + exportPadding,
  61. renderScrollbars: false,
  62. renderSelection: false
  63. }
  64. );
  65. return tempCanvas;
  66. }