Skip to main content

Graph

The Graph is a descendant of the mvc.Model and is usually defined at the beginning of the code of a JointJS application. The graph is a powerful data model behind all JointJS diagrams. It not only provides efficient storage for directed graphs, but also offers useful algorithms for graph traversal.

Creating a graph​

In order for JointJS to find the correct constructor for your cell, the cellNamespace option must be provided in the constructor function whenever a graph is instantiated. JointJS's built-in shapes are located in the shapes namespace, so this namespace is commonly used as the cellNamespace in our examples. Nevertheless, it is also possible to add custom shapes to this namespace, or to use a different namespace altogether.

For example, if shapes namespace is provided as the value of cellNamespace, and a cell is of type 'custom.Element', then the graph will look up the shapes.custom.Element object when deserializing a graph from JSON format. On the other hand, if the graph is instantiated as e.g. const graph = new dia.Graph({}, { cellNamespace: myCustomNamespace }), then the graph will look up the model definition from the myCustomNamespace.custom.Element object instead.

Note that the value of graph's cellNamespace should usually also be provided as the value of paper's cellViewNamespace option.

import { dia, shapes } from '@joint/core';
import { CustomElement } from './custom-element';

const namespace = {
CustomElement,
...shapes
}

const graph = new dia.Graph({}, {
cellNamespace: namespace
});

Adding cells​

In order to have our cells (elements and links) rendered, we need to add them to the graph; unless we add our cells, the diagram does not know they exist.

There are several way to add cells to the graph:

  • cell.addTo() - we can use the addTo() cell method. It allows to add specific cell to the graph at any point.

  • graph.addCells() - we can also use the addCells() function, which is a method of the graph object that allows us to add multiple cells at once.

  • graph.fromJSON() - if you have a JSON representation of the graph, you can use the fromJSON() function to add all cells from the JSON to the graph (replacing the current content of the graph).

  • graph.resetCells() - you can use the resetCells() method to replace the current content of the graph with an array of cells at once.

Stay in the know

Be where thousands of diagramming enthusiasts meet

Star us on GitHub