Skip to content

Export and snapshots

Export graph payloads or render a raster image.

#Exports and independent views

cy.json() returns a plain inspection/export object. It is export-only; cy.json(object) is not a restore form. cy.serialize() writes the compact binary wire representation.

#cytoscape.toColumnarElements(defs, options?)

// Convert element definitions to a compact columnar payload for bulk loading or binary serialization
cytoscape.toColumnarElements(defs: ElementsDefinition | ElementDefinition, options?: ToColumnarOptions): ColumnarElements

Convert element definitions to a compact columnar payload for bulk loading or binary serialization. Node fields use typed arrays, and edge endpoints refer to indices in the payload's node list.

This form does not preserve locked, grabbable or pannable overrides. Pass definitions directly to the constructor when those flags must survive. Use the refs option to include references to nodes already in the graph.

Parameters
NameDescription
defs: ElementsDefinition | ElementDefinition

one element, an array, or { nodes, edges }

options: ToColumnarOptions?Default: {}

{ refs }: carry endpoints and parents the payload does not hold as node references rather than throwing

Fields of defs
NameDescription
group: GroupName?

inferred from data.source/data.target when omitted

data: DefinitionData<Data>?
position: Position?

nodes only

collapsed: boolean?

nodes only: persisted miniature-compound state

appliedCollapseScale: number?

nodes only: current applied factor when collapsed; omitted uses the configured collapse-scale

selected: boolean?
selectable: boolean?
grabbable: boolean?
locked: boolean?
pannable: boolean?

dragging this element pans the graph instead (default: true for edges, false for nodes)

nodes: ElementDefinition<NodeData>[]?
edges: ElementDefinition<EdgeData>[]?
Fields of options
NameDescription
refs: boolean?

Carry what the payload names but does not hold as node references instead of throwing: an edge endpoint or a node parent that is not a node in the payload goes into the result's refs, indexed past its own nodes, to be resolved against the graph the payload loads into. This is how a chunk of a progressive cy.load() carries its cut edges in the columnar and wire forms. Default false: the payload must be self-contained.

Returns ColumnarElements

the equivalent columnar payload — self-contained, or with refs when that option is on and something was referenced

Example

const columns = cytoscape.toColumnarElements([{ data: { id: 'new' } }]);
console.log(cy.add(columns).length); // 1

Example graph and handle setup

Throws

if an edge lacks a source or target; without refs, also if an edge names a source or target that is not a node in the same payload — columnar payloads are self-contained unless they carry references; and on an unknown option

#cytoscape.serializeElements(elements)

// Serialize elements (definition form or columnar form) into one transferable/fetchable ArrayBuffer
cytoscape.serializeElements(elements: ElementsDefinition | ElementDefinition | ColumnarElements): ArrayBuffer

Serialize elements (definition form or columnar form) into one transferable/fetchable ArrayBuffer. deserializeElements (or passing the buffer straight to options.elements/cy.add()) reverses it.

Parameters
NameDescription
elements: ElementsDefinition | ElementDefinition | ColumnarElements

the elements to serialize, in either accepted form; a definition-form payload is converted to columnar first. A columnar payload's optional graph-level data rides along; the definition form has nowhere to put it, so it carries none. Its node references (refs) ride too — convert definitions with toColumnarElements( defs, { refs: true }) first to carry cut edges

Fields of elements
NameDescription
columnar: true

discriminant so the loader can tell the forms apart

nodes: ElementDefinition<NodeData>[]?
edges: ElementDefinition<EdgeData>[]?
refs: string[] | PackedIds?

Node references (experimental with the wire format until 4.x): the ids of nodes this payload does not carry but indexes — an edge endpoint or a node parent nodes.count + i names refs[i]. Each must name a node already in the graph when the payload loads (an earlier chunk of a cy.load(), or anything cy.add() put there); one that does not throws before anything is added. Each id resolves once however many edges index it, which is what makes a chunk's cut edges as cheap as its own. The factory's options.elements loads into an empty graph, so a payload with refs cannot load there; cy.patch() refuses one. Build it from definitions with toColumnarElements( defs, { refs: true }).

data: DefinitionData<Data>?
group: GroupName?

inferred from data.source/data.target when omitted

position: Position?

nodes only

collapsed: boolean?

nodes only: persisted miniature-compound state

appliedCollapseScale: number?

nodes only: current applied factor when collapsed; omitted uses the configured collapse-scale

selected: boolean?
selectable: boolean?
grabbable: boolean?
locked: boolean?
pannable: boolean?

dragging this element pans the graph instead (default: true for edges, false for nodes)

Returns ArrayBuffer

one little-endian ArrayBuffer holding the whole payload — fixed header, columns, and ids as a UTF-8 blob with prefix offsets. Every section starts at an offset aligned to its element width (8 for f64 columns), and that alignment is the encoder's contract: deserializeElements returns views over the buffer rather than copies because of it (census measured the decode at zero copies), so a reader may rely on it and a future encoder must keep it

Example

const buffer = cytoscape.serializeElements([{ data: { id: 'new' } }]);
console.log(cy.add(buffer).length); // 1

Example graph and handle setup

Throws

if the platform is big-endian, or if a definition-form payload names an edge endpoint that is not a node in the same payload

#cytoscape.deserializeElements(input)

// Deserialize a serializeElements buffer (or a view over one) back into the columnar elements form
cytoscape.deserializeElements(input: ArrayBuffer | ArrayBufferView): ColumnarElements

Deserialize a serializeElements buffer (or a view over one) back into the columnar elements form. Numeric columns are zero-copy views into the given buffer; a misaligned view is copied once to realign.

Parameters
NameDescription
input: ArrayBuffer | ArrayBufferView

a serializeElements buffer, or a view over one

Returns ColumnarElements

the columnar form, whose numeric columns are views into the input rather than copies — so the buffer must outlive the result, and writing into either is visible through the other. Graph-level data is the exception in two ways: it is decoded from JSON rather than viewed, and cy.add() deliberately ignores it (see ColumnarElements.data)

Example

const payload = cytoscape.deserializeElements(cy.serialize());
console.log(payload.nodes.count); // 3

Example graph and handle setup

Throws

if the platform is big-endian, or the buffer is too short, truncated or of an unsupported format version

#cy.serialize()

// Export graph elements and graph-level data as a binary buffer
cy.serialize(): ArrayBuffer

Export graph elements and graph-level data as a binary buffer. Load it into a new instance with cytoscape({ elements: buffer }), or add its elements to an existing instance with cy.add(buffer).

The buffer carries element identity, positions, topology, selection and data. It excludes stylesheet, viewport and scratch. Constructor loading applies its graph-level data; add() leaves the destination's graph data unchanged.

Returns ArrayBuffer

a fresh little-endian buffer, self-contained (every edge endpoint indexes a node in the same payload) and directly loadable — derived geometry is flushed first, so parent boxes are the current ones rather than whatever was last materialized

Example

const buffer = cy.serialize();
const restored = cytoscape({ headless: true, elements: buffer });
console.log(restored.nodes().length); // 3
restored.destroy();

Example graph and handle setup

#cy.json(flat?)

// Export a plain-object snapshot containing elements, stylesheet, viewport, interaction settings and graph-level data
cy.json(flat?: boolean): Record<string, unknown>

Export a plain-object snapshot containing elements, stylesheet, viewport, interaction settings and graph-level data.

This method is export-only: json(object) is not supported. Use patch() to reconcile incoming element data, clone() to copy a live instance, or serialize() to save a compact element payload for later loading.

Parameters
NameDescription
flat: boolean?

when true, elements export as one flat array instead of { nodes, edges }

Returns Record<string, unknown>

the exported graph

Example

console.log(cy.json().elements.nodes.length); // 3

Example graph and handle setup

Throws

if given anything but a boolean — the guard that catches an attempted json( obj) import

#Raster image export

Rendered png() and jpg() exports are asynchronous GPU readbacks and reject on a headless core. Image export describes output encodings, viewport versus full-graph bounds, scaling and format-specific backgrounds. SVG export is unavailable.

Rendered cores export the currently displayed graph through cy.png() or cy.jpg(). Both return promises because the renderer draws to an offscreen GPU target and reads the pixels back asynchronously. Headless cores reject: they have no renderer to export. The exporter renders at native output resolution, independent of the on-screen adaptive render scale, and evaluates label visibility at the export scale.

const blob = await cy.png({ full: true, maxWidth: 1600, output: 'blob' });
const url = URL.createObjectURL(blob);
const image = document.createElement('img');
image.src = url;
document.body.append(image);
// Revoke the URL when the application no longer needs it.

The default output is 'base64uri', a PNG data URI. output: 'base64' returns only the base64 payload; 'blob' resolves to a Blob, and 'blob-promise' is an alias for 'blob'. JPEG uses the same options with cy.jpg() (or cy.jpeg()). Its default background is white because JPEG has no alpha channel; quality is a format-specific encoder hint from 0 to 1. PNG defaults to a transparent background. Set bg to a CSS color to paint behind either format.

Viewport export is the default: it captures the current container dimensions and viewport transform. scale multiplies rendered CSS pixels, default 1. With full: true, the exporter instead uses the model-space graph bounds and scale means output pixels per model unit. maxWidth and maxHeight replace scale; if both are set, the smaller resulting scale is used so the full image fits within both dimensions. These limits are output pixels.

An empty graph cannot be exported with full: true, and a viewport export requires a nonzero container size. The background color and scale are validated. Output larger than the GPU's maximum texture size rejects with guidance to reduce scale or set a dimension cap. Browser canvas encoding can also reject if it cannot produce the requested image.

The current APIs export PNG and JPEG. SVG export and its image/font options are unavailable; see feature availability. PDF export is unavailable.

#cy.png(options?)

// Export the rendered graph as a PNG
cy.png(options?: ExportOptions): Promise<string | Blob>

Export the rendered graph as a PNG. Async — the pixels live on the GPU (offscreen render + readback); every output form resolves through the returned promise. Options: bg, full, scale or maxWidth/maxHeight, output ('base64uri' default | 'base64' | 'blob'; 'blob-promise' is an accepted alias of 'blob'). Headless instances reject — there is no renderer to export from.

Parameters
NameDescription
options: ExportOptions?Default: {}

the export options named above

Fields of options
NameDescription
output: 'base64uri' | 'base64' | 'blob' | 'blob-promise'?

result form: a data-URI string (default), the raw base64 payload, or a Blob ('blob-promise' is accepted as an alias of 'blob' — every output form resolves through the returned promise)

bg: string?

background color under the graph (any CSS color). Default: transparent for png; white for jpg (JPEG has no alpha)

full: boolean?

export the whole graph's bounds instead of the current viewport (default false)

scale: number?

output pixels per rendered CSS px (viewport export) or per model unit (full export); default 1. Ignored when maxWidth/maxHeight are given

maxWidth: number?

cap the output width in px (the scale is computed to fit; overrides scale)

maxHeight: number?

cap the output height in px (the scale is computed to fit; overrides scale)

quality: number?

jpg only: encode quality in [0, 1] (default: the browser's)

Returns Promise<string | Blob>

the encoded image in the requested output form

Example

// Use a mounted, renderer-ready core.
await cy.ready;
const image = await cy.png({ output: 'blob' });
console.log(image.type); // image/png

Example graph and handle setup

#cy.jpg(options?)

// Export as JPEG: as {@link png}, plus quality (0..1) and a white default bg (JPEG has no alpha channel)
cy.jpg(options?: ExportOptions): Promise<string | Blob>

Export as JPEG: as png, plus quality (0..1) and a white default bg (JPEG has no alpha channel).

Parameters
NameDescription
options: ExportOptions?Default: {}

as png, plus quality

Fields of options
NameDescription
output: 'base64uri' | 'base64' | 'blob' | 'blob-promise'?

result form: a data-URI string (default), the raw base64 payload, or a Blob ('blob-promise' is accepted as an alias of 'blob' — every output form resolves through the returned promise)

bg: string?

background color under the graph (any CSS color). Default: transparent for png; white for jpg (JPEG has no alpha)

full: boolean?

export the whole graph's bounds instead of the current viewport (default false)

scale: number?

output pixels per rendered CSS px (viewport export) or per model unit (full export); default 1. Ignored when maxWidth/maxHeight are given

maxWidth: number?

cap the output width in px (the scale is computed to fit; overrides scale)

maxHeight: number?

cap the output height in px (the scale is computed to fit; overrides scale)

quality: number?

jpg only: encode quality in [0, 1] (default: the browser's)

Returns Promise<string | Blob>

the encoded image in the requested output form

Example

// Use a mounted, renderer-ready core.
await cy.ready;
const image = await cy.jpg({ output: 'blob' });
console.log(image.type); // image/jpeg

Example graph and handle setup

Also spelled cy.jpeg.

All guides · Alphabetical API index · Read continuously