Skip to main content

Save and export

Drawing works without a canvas: build strokes with addStroke, then save or export them headless.

Save and load​

toData() serializes the strokes into a compact binary ArrayBuffer. Drawing.fromData(data) restores them, and throws on invalid data.

const data = drawing.toData()
// ...store `data` in a file or a database...
const restored = Drawing.fromData(data)

Only strokes are saved: the undo history, listeners and stroke ids are not.

To show a restored drawing, pass it to SketchCanvas's drawing prop.

Export​

Exports render off the JavaScript thread and return promises.

MethodReturnsOptions
toImage(options)Promise<ArrayBuffer>ImageExportOptions
toSvg(options)Promise<string>VectorExportOptions
toPdf(options)Promise<ArrayBuffer>VectorExportOptions
// PNG at 2 pixels per point, transparent background.
const png = await drawing.toImage({ format: 'png', quality: 100, scale: 2 })

// JPEG of a fixed area; JPEG defaults to a white background.
const jpeg = await drawing.toImage({
format: 'jpeg',
quality: 85,
scale: 3,
rect: { x: 0, y: 0, width: 400, height: 300 },
})

// SVG and a one-page PDF with a white background.
const svg = await drawing.toSvg({ backgroundColor: 0xffffffff })
const pdf = await drawing.toPdf({ backgroundColor: 0xffffffff })
  • rect defaults to the bounds of all strokes.
  • Images are capped at 8192 pixels per side.
  • The ruler is never exported.

:::warning Empty drawings An empty drawing has a zero bounds, so exporting it without a rect rejects with export needs a rect with a positive size. Pass a rect, or check strokeCount first. :::

info

SVG and PDF draw pencil, crayon and watercolor strokes flat, without their texture and soft edges.

Building strokes from code​

const drawing = new Drawing()
drawing.addStroke({ type: 'monoline', color: 0x000000ff, width: 3 }, [
{ x: 10, y: 10, timeOffset: 0, size: 3, force: 1, azimuth: 0, altitude: Math.PI / 2 },
{ x: 200, y: 120, timeOffset: 0.2, size: 3, force: 1, azimuth: 0, altitude: Math.PI / 2 },
])
const svg = await drawing.toSvg({})

addStroke throws when points is empty or holds non-finite values. See StrokePoint for the fields.