Skip to content

Virtual whiteboard for sketching hand-drawn like diagrams

fix(packages/excalidraw): export PNGs from a CPU-backed canvas (#12471)

David Luzar95307fa136a3
diff --git a/packages/excalidraw/scene/export.ts b/packages/excalidraw/scene/export.ts
index fb025ee480..01d68a369a 100644
--- a/packages/excalidraw/scene/export.ts
+++ b/packages/excalidraw/scene/export.ts
@@ -865,6 +865,13 @@ const exportToCanvas = async ({
const canvas = renderEnvironment.createCanvas();
+ // Request a CPU-backed context before anything else (rough.canvas() below)
+ // creates one without options. Chrome's GPU canvas backend (Skia Graphite)
+ // antialiases paths with 4x MSAA, so GPU-backed exports come out jaggy, and
+ // large ones also allocate multisample buffers many times the bitmap's size
+ // in GPU memory. The pixels are read back to the CPU for encoding anyway.
+ canvas.getContext("2d", { willReadFrequently: true });
+
// round rather than letting the canvas truncate, which would turn float
// noise (e.g. 28.999999999999996) into a pixel lost
canvas.width = Math.max(1, Math.round(exportWidth));
diff --git a/packages/excalidraw/tests/scene/export.test.ts b/packages/excalidraw/tests/scene/export.test.ts
index 2ffb7fab8f..7ea3c9c3ca 100644
--- a/packages/excalidraw/tests/scene/export.test.ts
+++ b/packages/excalidraw/tests/scene/export.test.ts
@@ -399,6 +399,26 @@ describe("exportToCanvas", () => {
),
).toEqual([]);
});
+
+ it("renders on a CPU-backed canvas", async () => {
+ const getContextSpy = vi.spyOn(HTMLCanvasElement.prototype, "getContext");
+
+ const canvas = await exportScene({
+ type: "canvas",
+ data: {
+ elements: [API.createElement({ type: "rectangle" })],
+ files: null,
+ },
+ });
+
+ // only the first getContext() call's options take effect
+ const firstCall = getContextSpy.mock.contexts.indexOf(canvas);
+ expect(getContextSpy.mock.calls[firstCall]).toEqual([
+ "2d",
+ { willReadFrequently: true },
+ ]);
+ getContextSpy.mockRestore();
+ });
});
describe("export background", () => {