Paper
constructor
joint.dia.Paper is the view for the joint.dia.Graph
model. It inherits from mvc.View. Accepts an options
object in its constructor with numerous settings.
When a paper is associated with a graph, the paper makes sure that all the cells added to the graph are automatically rendered.
var graph = new joint.dia.Graph
var paper = new joint.dia.Paper({
el: $('#paper'),
width: 600,
height: 400,
gridSize: 10,
model: graph
});
var rect = new joint.shapes.basic.Rect({
position: { x: 50, y: 70 },
size: { width: 100, height: 40 }
});
graph.addCell(rect);
Paper automatically handles this change and renders the rectangle to the SVG document that it internally holds.
afterRender
afterRender
- Callback function executed after all scheduled updates had been processed (both asynchronous and synchronous rendering). The callback function is provided with the following arguments:
stats | object | Statistics about the current update. |
options | object | Parameters the current updates were scheduled with. |
paper | joint.dia.Paper | This paper instance |
allowLink
allowLink
- expects a function returning a boolean. The function is run when the user stops interacting with a linkView's arrowhead (source or target). If the function returns false
, the link is either removed (for links which are created during the interaction) or reverted to the state before the interaction.
// Return `false` if a graph cycle is detected (`graphlib` refers to a dependency of the DirectedGraph plugin).
paper.options.allowLink = function(linkView, paper) {
var graph = paper.model;
return graphlib.alg.findCycles(graph.toGraphLib()).length === 0;
}
anchorNamespace
anchorNamespace
- built-in anchors are defined by default on the joint.anchors
namespace. It is also possible to define custom anchors on this namespace. If you would like JointJS to look for anchor definitions under a different namespace, you can set the anchorNamespace
option to your desired namespace.
async
async
- when true
, the paper uses asynchronous rendering to display graph cells (i.e. cells added either with graph.resetCells()
or graph.addCells()
methods).
This is very useful for adding a large number of cells into the graph. The rendering performance boost is significant and it doesn't block the UI. However, asynchronous rendering brings about some caveats – at the time when you call another function...
- ...the views of freshly added cell models may not have yet been added to this paper's DOM.
- ...some views may have been removed from the DOM by the
paper.options.viewport
function. - ...views already present in the DOM may not have been updated to reflect changes made in this paper's graph since the last render.
- ...re-rendering may have been manually disabled with
paper.options.frozen
orpaper.freeze()
.
This is an issue because certain CellView/Paper methods require the view to be updated and present in the DOM to function
properly (e.g. paper.findViewByModel()
or cell.findView()
, as well
as paper.getContentBBox()
and elementView.getBBox()
/linkView.getBBox()
).
The problem may be circumvented in several Paper methods via the useModelGeometry
option to force using model calculations instead of view measurements (e.g. paper.getContentBBox()
, paper.getContentArea()
, paper.scaleContentToFit()
, paper.fitToContent()
). In this case, the methods refer to the (always up-to-date) model data.
For the methods that truly need a to refer to a CellView, one way to prevent inconsistencies is to rely on the 'render:done'
paper event. This event signals that all scheduled updates are done and that the state of cell views is consistent with the state of the cell models.
Alternatively, you may trigger a manual update immediately before a sensitive function call. JointJS offers several suitable methods:
paper.requireView()
- bring a single view into the DOM and update it.paper.dumpViews()
- bring all views into the DOM and update them.paper.updateViews()
- update all views.
autoFreeze
autoFreeze
- By default, the paper periodically checks the viewport calling viewport
callback for every view. The options autoFreeze
can be used to suppress this behavior. When the option is enabled, it freezes the paper as soon as there are no more updates and unfreezes it when there is an update scheduled. (paper has no updates to perform when hasScheduledUpdates() returns false
). In that case, the user needs to checkViewport
manually when he wants to reinvoke viewport
when external changes occurred, e. g. during scrolling and zooming. The freeze state will be set on the next frame cycle after processing all updates. On this cycle paper will call viewport
callback and freeze itself.
background
An object defining the paper background color and image. It defaults to false
meaning there is no background set. The configuration object can have the following properties.
- color
property sets the paper background color. It accepts all the values accepted by the CSS
background-color
property. e.g'red'
,'rgba(255, 255, 0, 0.5)'
,'radial-gradient(ellipse at center, red, green);'
- image
property defines the path to the background image file. e.g.
'/my-background.png'
. - position
is an object
{ x: Number, y: Number }
defining the background image position. It also allows to use all the CSSbackground-position
property values. In that case all the paper transformations have no impact on the background image position. It defaults tocenter
. - size
is an object
{ width: Number, height: Number }
defining the background image size. It also allows to use all the CSSbackground-size
property values. In that case all the paper transformations have no impact on the background size. It defaults toauto auto
. - repeat
property defines how the background image is repeated. The value could be any value accepted by the CSS
background-repeat
property and few more defined by JointJS. Those areflip-x
,flip-y
,flip-xy
andwatermark
. It defaults tono-repeat
. - quality
is a coefficient specifying the quality of the image (e.g
0.5
uses only 50% the image size for creating a pattern). Applicable only for the JointJSrepeat
option values. It defaults to1
. - opacity
is a number in the range
[0,1]
specifying the transparency of the background image (0
is fully transparent and1
is fully opaque). It defaults to1
. - watermarkAngle
is an angle in degrees speficying the slope of the watermark image. Applicable only for the
'watermark'
repeat
option. It defaults to20
deg.
background: {
color: '#6764A7',
image: 'jointjs-logo.png',
repeat: 'watermark',
opacity: 0.3
}
beforeRender
beforeRender
- Callback function executed before processing scheduled updates (both asynchronous and synchronous rendering). The callback function is provided with the following arguments:
options | object | Parameters the current updates were scheduled with. |
paper | joint.dia.Paper | This paper instance. |
cellViewNamespace
cellViewNamespace
- In order for the JointJS paper
to read cell view definitions from the correct location, the paper
option cellViewNamespace
must be provided. Built-in cell view definitions are usually located in the joint.shapes
namespace, so this is a common namespace to use. It's possible to a add custom cell view to this namespace, or alternatively, you may like to use a different namespace completely.
For example, if joint.shapes
is provided as the value of cellViewNamespace
, and a cell is of type 'custom.Element'
, then the paper
looks up the joint.shapes.custom.ElementView
object type when rendering the cell onto the screen. If cellViewNamespace
is set with a value of myCustomNamespace
, the paper will read view definitions from the myCustomNamespace.custom.ElementView
object instead. This option is often used in combination with the cellNamespace
option on the joint.dia.Graph
object.
clickThreshold
clickThreshold
- When number of mousemove events exceeds the clickThreshold
there is no pointerclick
event triggered after mouseup. It defaults to 0
.
connectionPointNamespace
connectionPointNamespace
- built-in connectionPoints are defined by default on the joint.connectionPoints
namespace. It is also possible to define custom connectionPoints on this namespace. If you would like JointJS to look for connectionPoint definitions under a different namespace, you can set the connectionPointNamespace
option to your desired namespace.
connectionStrategy
connectionStrategy
- the connection strategy to use on this paper. It can either be a function or null
. JointJS provides a collection of built-in connection strategies in the joint.connectionStrategies
namespace; alternatively, a custom function may be provided. See the link geometry connectionStrategy documentation for more information.
connectorNamespace
connectorNamespace
- built-in connectors are defined by default on the joint.connectors
namespace. It is also possible to define custom connectors on this namespace. If you would like JointJS to look for connector definitions under a different namespace, you can set the connectorNamespace
option to your desired namespace.
defaultAnchor
defaultAnchor
- an anchor function that is used by links if no anchor
property is defined for a link end. It can either be an object (with a name
and optional args
) or a function. JointJS provides a collection of built-in anchor functions in the joint.anchors
namespace; alternatively, a custom function may be provided. See the link geometry anchor documentation for more information.
defaultConnectionPoint
defaultConnectionPoint
- a connection point function that is used by links if no connectionPoint
property is defined for a link end. It can either be an object or a function. JointJS provides a collection of built-in connection point functions in the joint.connectionPoints
namespace; alternatively, a custom function may be provided. See the link geometry connectionPoint documentation for more information.
defaultConnector
defaultConnector
- a connector that is used by links if no connector
property is defined on them. It can either be an object or a function. JointJS provides a collection of built-in connectors in the joint.connectors
namespace; alternatively, a custom function may be provided. See the link geometry connector documentation for more information.
defaultLink
defaultLink
- link that should be created when the user clicks and drags an active magnet (when creating a link from a port via the UI). Defaults to new joint.shapes.standard.Link()
. It can also be a function with signature function(cellView, magnet) {}
that must return an object of type joint.dia.Link
.
defaultLinkAnchor
defaultLinkAnchor
- a link anchor function that is used by links if no linkAnchor
property is defined for a link end. It can either be an object (with a name
and optional args
) or a function. JointJS provides a collection of built-in link anchor functions in the joint.linkAnchors
namespace; alternatively, a custom function may be provided. See the link geometry linkAnchor documentation for more information.
defaultRouter
defaultRouter
- a router that is used by links if no router
property is defined on them. It can either be an object or a function. JointJS provides a collection of built-in routers in the joint.routers
namespace; alternatively, a custom function may be provided. See the link geometry router documentation for more information.
drawGrid
drawGrid
- option whether the paper grid should be drawn or not. It could be a boolean
or an object
. It defaults to false
.
Define color
and thickness
to adjust the default grid pattern:
color | string | color of the default grid pattern. |
---|---|---|
thickness | number | thickness of the default grid pattern. |
There are also some pre-defined grid patterns: dot
, fixedDot
, mesh
, doubleMesh
. If you'd like to use these patterns, define drawGrid
options as follows:
name | string | name of the pre-defined pattern. Can be either dot , fixedDot , mesh , doubleMesh |
---|---|---|
args | object | array | an extra argument for the pre-defined grid patterns. It can be either an object (e.g. dot , mesh ) or an array (e.g. doubleMesh ) |
Pre-defined grids with default settings:
The paper from the images below has been scaled 2 times and has gridSize set to 10.
dot
fixedDot
mesh
doubleMesh
drawGrid: true // default pattern (dot) with default settings
drawGrid: 'mesh' // pre-defined pattern with default settings
drawGrid: { name: 'mesh', args: { color: 'black' }}
drawGrid: {
name: 'doubleMesh',
args: [
{ color: 'red', thickness: 1 }, // settings for the primary mesh
{ color: 'green', scaleFactor: 5, thickness: 5 } //settings for the secondary mesh
]}
drawGridSize
drawGridSize
- the size of the visual grid drawn using the drawGrid option. If this option is set to null
(default), the gridSize option is used instead. If the option is changed after the paper has been initialized, call drawGrid to update the grid.
el
el
- CSS selector, or a DOM element holding the container for the paper
elementView
elementView
- object that is responsible for rendering an element model into the paper. Defaults to joint.dia.ElementView
. It can also be a function of the form function(element)
that takes an element model and should return an object responsible for rendering that model onto the screen (in most cases a subtype of joint.dia.ElementView
)
embeddingMode
embeddingMode
- when set to true
, the paper is set to embedding mode. In this mode, when you drag an element and drop into another element, the element below becomes a parent of the dropped element (the dropped element gets automatically embedded into the parent element). Similarly, when you drag an element out of its parent, the element gets automatically unembedded from its parent. The embedding mode also makes sure all the connected links and child elements have proper z
index set so that they stay visible. To control what elements can be embedded into what other elements, use the validateEmbedding()
function on the paper (see below). This is useful for hierarchical diagrams. See the Devs demo on how this can be used.
findParentBy
findParentBy
- determines the way how a cell finds a suitable parent when it's dragged over the paper. The cell with the highest z-index (visually on the top) will be chosen. findParentBy
option comes to play when the paper is in embedding mode. All possible values are
Value | Description |
---|---|
'bbox' (default) | Choose the parent from the elements under the element rectangle. |
'pointer' | Choose the parent from the elements under the cursor (pointer). |
'center' | 'origin' | 'corner' | 'topRight' | 'bottomLeft' | Choose the parent from the elements under a specific point of the element rectangle. |
function | The function accepts an
|
frontParentOnly
frontParentOnly
- when set to the default true
, only the element at the very front is taken into account for embedding. If disabled, the elements under the dragged view are tested one by one (from front to back) until a valid parent is found.
// If a child element is embedded and covers the area of 'app.Container', a third element is unable to be embedded
validateEmbedding: function(childView, parentView) {
const model = parentView.model;
if (model.get('type') === 'app.Container') return true;
return false;
},
frontParentOnly: true,
frozen
frozen
- when true
on an async
paper, the paper is frozen. This means that changes made in this paper's graph are not reflected by the paper until this state is reversed. Use paper.unfreeze()
to unfreeze the paper, and paper.freeze()
to freeze it again. (You may also use paper.updateViews()
to manually refresh the paper and leave it frozen.)
Example:
const graph = new joint.dia.Graph({}, { cellNamespace: joint.shapes });
graph.resetCells([cell1, cell2]);
const paper = new joint.dia.Paper({
el: document.getElementById('paper-holder'),
model: graph,
cellViewNamespace: joint.shapes,
frozen: true
});
paper.unfreeze();
gridSize
gridSize
- size of the grid in pixels
guard
guard
- guard paper from handling a browser UI event. This function is of the form function(evt, view)
and should return true
if you want to prevent the paper from handling the event evt
, false
otherwise. This is an advanced option that can be useful if you have your own logic for handling events.
height
height
- height of the paper (see setDimensions()).
highlighterNamespace
highlighterNamespace
- built-in highlighters are defined by default on the joint.highlighters
namespace. Existing and custom highlighters are defined by extending the base class. If you would like JointJS to look for highlighter definitions under a different namespace, you can set the highlighterNamespace
option to your desired namespace.
highlighting
highlighting
- Configure which highlighter to use (if any) for each type of interaction.
List of highlighting interactions:
-
default
joint.dia.CellView.Highlighting.DEFAULT
– The default highlighter to use (and options) when none is specified. Default:{
name: 'stroke',
options: {
padding: 3
}
} -
connecting
joint.dia.CellView.Highlighting.CONNECTING
– When a valid link connection can be made to an element. -
embedding
joint.dia.CellView.Highlighting.EMBEDDING
– When a cell is dragged over another cell in embedding mode. -
magnetAvailability
joint.dia.CellView.Highlighting.MAGNET_AVAILABILITY
– When showing all magnets to which a valid connection can be made. Default:{
name: 'addClass',
options: {
className: 'available-magnet'
}
} -
elementAvailability
joint.dia.CellView.Highlighting.ELEMENT_AVAILABILITY
– When showing all elements to which a valid connection can be made. Default:{
name: 'addClass',
options: {
className: 'available-cell'
}
}
If a type is set to false
, no highlighter is used.
If a type is set to null | undefined
, the default highlighter is used.
Example usages:
new joint.dia.Paper({
highlighting: {
'default': {
name: 'stroke', // `joint.highlighters.stroke`
options: {
padding: 2
}
},
'connecting': {
name: 'addClass', // `joint.highlighters.addClass`
options: {
className: 'highlight-connecting'
}
},
// Disable highlighter for embedding
'embedding': false
}
});
new joint.dia.Paper({
// Disable all highlighters
highlighting: false
});
List of available highlighters and their options:
- joint.highlighters.mask
- joint.highlighters.stroke
- joint.highlighters.addClass
- joint.highlighters.opacity
If you need to highlight an element or a link differently based on the cell type or one of its attribute, you can disable the paper highlighting and add a highlighter manually.
// Disable Embedding
paper.options.highlighting.embedding = false;
const MyHighlighters = {
EMBEDDING: 'embedding-highlighter'
};
paper.on('cell:highlight', (cellView, node, { type }) => {
if (type === joint.dia.CellView.Highlighting.EMBEDDING) {
const isLink = cellView.model.isLink();
joint.highlighters.mask.add(cellView, node, MyHighlighters.EMBEDDING, {
attrs: {
'stroke': isLink ? 'red' : 'blue'
}
});
}
});
paper.on('cell:unhighlight', (cellView, node, { type }) => {
if (type === joint.dia.CellView.Highlighting.EMBEDDING) {
joint.highlighters.mask.remove(cellView, MyHighlighters.EMBEDDING);
}
});
By default, when a user connects a link, the target node for the highlighter is either the root of the cell or a magnet. To change this use highlighterSelector attribute.
const element = new joint.shapes.standard.Rectangle({
attrs: {
root: {
highlighterSelector: 'body'
}
}
});
// When a user tries to connect a link to the element.
paper.on('cell:highlight', (elementView, node) => {
assert.notOk(node === elementView.el);
assert.ok(node === elementView.el.querySelector('[joint-selector="body"]'));
});
interactive
interactive
- Configure which of the default interactions with elements and links should be enabled.
The property value defaults to { labelMove: false }
. This can be overwritten in three ways: with a boolean value, with an object specifying interaction keys, or with a function.
If set to false
, all interactions with elements and links are disabled. If set to true
, all interactions are enabled.
// disable all interaction
var paper = new joint.dia.Paper({
// ...
interactive: false,
});
// enable all interaction (including labelMove)
var paper = new joint.dia.Paper({
// ...
interactive: true,
});
Using an object, specific interactions may be disabled by assigning false
to their corresponding property name. It is not necessary to pass true
values; all omitted properties are assigned true
by default. (Note that the passed object is not merged with the default; unless labelMove
is explicitly excluded, it becomes enabled.) A full list of recognized interaction keys is provided below.
// disable labelMove
var paper = new joint.dia.Paper({
// ...
interactive: { labelMove: false }
});
// disable all element interactions
var paper = new joint.dia.Paper({
// ...
interactive: { elementMove: false, addLinkFromMagnet: false }
});
If defined as a function, the function is passed cellView
(the elementView/linkView the user is about to interact with) as the first parameter, followed by the name of the event ('pointerdown'
, 'pointermove'
, ...) that triggered the interaction. The return value of the function is then interpreted in the way specified above (false
causes all interaction to be disabled, an object disables specific interactions, etc.).
// disable link interactions for cellViews when a custom property is set
var paper = new joint.dia.Paper({
// ...
interactive: function(cellView) {
if (cellView.model.get('disableLinkInteractions')) {
return {
linkMove: false,
labelMove: false,
};
}
// otherwise
return true;
}
});
The example below has all interactions on the link and on the elements enabled. This is the default behavior:
The following tables present a list of all recognized interaction keys, followed by an example of a paper with only the related interactive property set to true
(and all other properties set to false
).
Links:
linkMove | Is the user allowed to move the link? |
---|---|
labelMove | Is the user allowed to move the link label? Use the |
Elements:
elementMove | Is the user allowed to move the element? |
---|---|
addLinkFromMagnet | Is the user allowed to add connections from magnets/ports? |
The stopDelegation
option is special. If it is true
(default), the element's elementMove
option determines whether the element responds to user drag.
However, if stopDelegation
is false
and the element is embedded within a parent, the user's dragging is delegated to the embedding parent. The parent's elementMove
option then determines whether both elements respond to user drag. The behavior is recursive. If the embedding parent has stopDelegation: false
, it delegates to its own embedding parent's elementMove
option and so on. If all children within an embedding have stopDelegation
set to false
, then no matter which element is dragged by the user, the whole embedding is dragged.
If the element is not embedded within an element, the stopDelegation
option is ignored (treated as true
). There is no other element to delegate to. Then elementMove
determines whether the element responds to user drag.
In the following example, both embedded elements have stopDelegation: false
. Thus, when the embedded element is dragged by the user, the parent ancestor (Movable) is dragged instead. When the parent ancestor has elementMove
disabled (Not movable), nothing happens.
stopDelegation |
---|
labelsLayer
labelsLayer
- controls the stacking context of the link labels.
Value | Description |
---|---|
false (default) | The labels are rendered as part of the links. Overlapping links with a larger z can cover link labels with a smaller one. |
true | The labels are rendered into its own layer on top of other elements and links. A link's connection can cover no label. |
linkAnchorNamespace
linkAnchorNamespace
- built-in linkAnchors are defined by default on the joint.linkAnchors
namespace. It is also possible to define custom linkAnchors on this namespace. If you would like JointJS to look for linkAnchor definitions under a different namespace, you can set the linkAnchorNamespace
option to your desired namespace.
linkPinning
linkPinning
- when set to true
(the default), links can be pinned to the paper meaning a source or target of a link can be a point. If you do not want to let the user drag a link and drop it somewhere in a blank paper area, set this to false
. The effect is that the link will be returned to its original position whenever the user drops it somewhere in a blank paper area.
linkView
linkView
- object that is responsible for rendering a link model into the paper. Defaults to joint.dia.LinkView
. It can also be a function of the form function(link)
that takes a link model and should return an object responsible for rendering that model onto the screen (in most cases a subtype of joint.dia.LinkView
).
magnetThreshold
magnetThreshold
- When defined as a number, it denotes the required mousemove events before a new link is created from a magnet. When defined as keyword 'onleave'
, the link is created when the pointer leaves the magnet DOM element. It defaults to 0
.
markAvailable
markAvailable
- marks all the available magnets or elements when a link is dragged (being reconnected). Default is false
. This gives a hint to the user to what other elements/ports this link can be connected. What magnets/cells are available is determined by the validateConnection
function. Internally, available magnets (SVG elements) are given the 'available-magnet'
class name and all the available cells the 'available-cell'
class name. This allows you to change the styling of the highlight effect.
model
model
- joint.dia.Graph
object
moveThreshold
moveThreshold
- Number of required mousemove events before the first pointermove event is triggered. It defaults to 0
.
multiLinks
multiLinks
- when set to false
, an element may not have more than one link with the same source and target element.
overflow
overflow
- if set to true
, the content of the paper is not clipped and may be rendered outside the paper area. If set to false
, the content is clipped, if necessary, to fit the paper area.
preventContextMenu
preventContextMenu
- Prevents default context menu action (when right button of the mouse is clicked). It defaults to true
.
preventDefaultBlankAction
preventDefaultBlankAction
- Prevents default action when an empty paper area is clicked. Setting the option to false
will make the paper pannable inside a container on touch devices. It defaults to true
.
preventDefaultViewAction
preventDefaultViewAction
- Prevents default action when a cell view is clicked. For example, setting the option to false
will cause clicking on the view to blur the document active element. It defaults to true
.
restrictTranslate
restrictTranslate
- restrict the translation (movement) of elements by a given bounding box. If set to true
, the user will not be able to move elements outside the boundary of the paper area. It's set to false
by default. This option also accepts a function with signature function(elementView, x0, y0)
in which case it must return one of the following:
- rectangle - (an object of the form
{ x: Number, y: Number, width: Number, height: Number }
) that defines the area in which the element represented byelementView
can be moved. - null - no restriction for element translation
- (x, y) => Position - For a given element position
x,y
return a new position{ x: Number, y: Number }
. The function is invoked every time the user moves the pointer.
For example, to restrict translation of embedded elements by the bounding box defined by their parent element, you can do:
restrictTranslate: function(elementView) {
const parent = elementView.model.getParentCell();
return parent
? parent.getBBox() // children movement is constrained by the parent area
: null; // parent movement is not restricted
}
Or restrict an element movement along a path:
restrictTranslate: function(elementView, x0, y0) {
// x0 and y0 are pointer coordinates at the start of the translation
const path = new g.Path('M 20 20 L 200 200 L 380 20');
const { x: x1, y: y1, width, height } = elementView.model.getBBox();
// The initial difference between the pointer coordinates and the element position
const dx = x1 - x0;
const dy = y1 - y0;
return function(x, y) {
// Find the point on the path.
const point = path.closestPoint({ x: x - dx, y: y - dy });
// Put the center of the element on this point
point.offset(-width / 2, -height / 2);
return point;
};
}
routerNamespace
routerNamespace
- built-in routers are defined by default on the joint.routers
namespace. It is also possible to define custom routers on this namespace. If you would like JointJS to look for router definitions under a different namespace, you can set the routerNamespace
option to your desired namespace.
snapLabels
snapLabels
- when enabled, force a dragged label to snap to its link. The default is false
, which means that the label may also be dragged around the link.
snapLinks
snapLinks
- when enabled, force a dragged link to snap to the closest element/port in the given radius. The option accepts true
in which case default values are used or an object of the form { radius: <value> }
where you can specify the radius (default is 50).
snapLinksSelf
snapLinksSelf
- when enabled, forces a dragged link end to snap to the x
or y
coordinate of the closest point on the current link (one of the ends and vertices) if the distance to the point on one axis is lesser than the specified radius. The option accepts true
in which case default values are used or an object of the form { radius: <value> }
where you can specify the radius (the default is 20).
sorting
sorting
- the sorting type to use when rendering the views in this paper (i.e. In what order should the views be rendered?).
The SVG 1.1 format does not have built-in z-index functionality, so JointJS implements it programmatically. You can set
the z-index directly using regular mvc.Model set('z')
/get('z')
methods or
through cell.toFront()
/cell.toBack()
methods. See
the model Z documentation for more information.
The Paper object exposes a sorting
object with three values that may be used as values of this option:
joint.dia.Paper.sorting.APPROX
- (default) render views according to their z-values. Views with different z-value are rendered in order, but the ordering of views with the same z-value is indeterminate. Similar in functionality to theEXACT
option, but much faster.joint.dia.Paper.sorting.EXACT
- render views in exactly the same order as reported bygraph.getCells()
(views with different z-values are rendered in order, and views with the same z-value are rendered in the order in which they were added). This is by far the slowest option, present mainly for backwards compatibility.joint.dia.Paper.sorting.NONE
- render views in an indeterminate order. (Note that this setting disables alltoFront
/toBack
functions mentioned above.)
validateConnection
validateConnection(cellViewS, magnetS, cellViewT, magnetT, end, linkView)
- a function that allows you control which link connections can be made between the source cellView/magnet (cellViewS/magnetS
), and the target cellView/magnet (cellViewT/magnetT
). end
is either the "source"
or the "target"
, and indicates which end of the link is being dragged. This is useful for defining whether a link starting in port POut of element A can lead to port PIn of element B. By default, all connections are allowed.
// The default allows all element connections
validateConnection: function(cellViewS, _magnetS, cellViewT, _magnetT, end, _linkView) {
return (end === 'target' ? cellViewT : cellViewS) instanceof ElementView;
}
// Other examples
validateConnection: function(cellViewS, magnetS, cellViewT, magnetT, end, linkView) {
// Prevent Link to Link connections
if (cellViewT.model.isLink() || cellVIewS.model.isLink()) return false;
// Prevent loop linking - This means the source and target cannot connect to the same magnet (e.g. port)
if (magnetS === magnetT) return false;
// Only allow target end to be reconnected
if (end === 'source') return false;
// Don't allow connection to cellView with 'isInactive' attribute of value true
if (cellViewS.model.get('isInactive') || cellViewT.model.get('isInactive')) return false;
// Prevent linking from input ports (assumes you have port groups setup)
if (magnetS && magnetS.getAttribute('port-group') === 'in') return false;
// Allow all other connections
return true;
}
validateEmbedding
validateEmbedding
- a function that allows you to control what elements can be embedded to what other elements when the paper is put into the embeddingMode
(see above). The function signature is: function(childView, parentView)
and should return true
if the childView
element can be embedded into the parentView
element. By default, all elements can be embedded into all other elements (the function returns true
no matter what).
validateMagnet
validateMagnet(cellView, magnet, evt)
- decide whether to create a link if the user clicks a magnet. magnet
is the DOM element representing the magnet. By default, this function returns true
for magnets that are not explicitly set to "passive" (which is usually the case of input ports).
validateUnembedding
validateUnembedding
- a function that allows you to control which elements can be unembedded when the paper is put into the embeddingMode
(see above).
The function signature is function(childView)
and should return true
if the childView
element can be unembedded from the parent and become a new root.
By default, all elements can become roots (the function returns true
no matter what).
The callback is called at the end of drag & drop action and if false
is returned, the position of the element, as well as the parent reference is reverted to the values before dragging.
The callback is called only on elements which were previously embedded in another element.
viewport
viewport
- a callback function that is used to determine whether a given view should be shown in an async
paper. If the function returns true
, the view is attached to the DOM; if it returns false
, the view is detached/unmounted from the DOM. The callback function is provided with three arguments:
view | mvc.View | The view in question |
isMounted | boolean | Is the view currently visible in the paper? |
paper | dia.Paper | This paper (for context) |
This function is meant to support hiding of views when they are outside the viewport. In most situations, it is unnecessary to render DOM elements that are not visible by the user; removing those elements from the DOM dramatically improves rendering times of huge graphs (thousands of views) and improves smoothness of user interaction. (If you do need to show a view that falls outside of this viewport, you can manually force the view to be shown using paper.requireView()
. If you need to show views according to a different viewport function, use paper.checkViewport()
. If you need to force all views to be shown, use paper.dumpViews()
.)
Example usage:
var viewportRect = new g.Rect(0, 0, 600, 400);
var graph = new joint.dia.Graph({}, { cellNamespace: joint.shapes });
var paper = new joint.dia.Paper({
model: graph,
cellViewNamespace: joint.shapes,
async: true,
viewport: function(view) {
var model = view.model;
var bbox = model.getBBox();
if (model.isLink()) {
// vertical/horizontal links have zero width/height
// we need to manually inflate the bounding box
bbox.inflate(1);
}
// Return true if there is an intersection
// Return true if bbox is within viewportRect
return viewportRect.intersect(bbox);
}
});
The viewport
function can also be used to support collapsing/uncollapsing behavior:
var graph = new joint.dia.Graph({}, { cellNamespace: joint.shapes });
var paper = new joint.dia.Paper({
model: graph,
cellViewNamespace: joint.shapes,
async: true,
viewport: function(view) {
// Return true if model is not hidden
return !model.get('hidden');
}
});
paper.on('element:pointerclick', function(view, evt) {
evt.stopPropagation();
toggleBranch(view.model);
});
function toggleBranch(root) {
var shouldHide = !root.get('collapsed');
root.set('collapsed', shouldHide);
graph.getSuccessors(root).forEach(function(successor) {
successor.set('hidden', shouldHide);
successor.set('collapsed', false);
});
}
width
width
- width of the paper (see setDimensions()).
Methods
checkViewport()
paper.checkViewport()
For every view in the paper, determine if it fits into the viewport specified by paper.options.viewport
function. Views that fit (views for which that function returns true
) are attached to the DOM; views that do not are detached.
While async
papers do this automatically, synchronous papers require an explicit call to this method for this functionality to be applied. To show all views again, use paper.dumpViews()
.
paper.checkViewport(opt)
If opt.viewport
is provided, it is used as the callback function instead of paper.options.viewport
. The format of the callback method is described in the option's documentation, as are examples of usage.
In async
papers, providing opt.viewport
causes viewport to be temporarily recalculated according to the provided callback function. This may be useful in situations where you need to show different views depending on context (e.g. viewing a section of the diagram vs. printing all of it).
clientOffset()
paper.clientOffset()
Returns coordinates of the paper viewport, relative to the application's client area.
clientToLocalPoint()
paper.clientToLocalPoint(p)
Transform client coordinates represented by point p
to the paper local coordinates. This is especially useful when you have a mouse event object and want coordinates inside the paper that correspond to event clientX
and clientY
point.
var localPoint1 = paper.clientToLocalPoint({ x: evt.clientX, y: evt.clientY });
// alternative method signature
var localPoint2 = paper.clientToLocalPoint(evt.clientX, evt.clientY);
clientToLocalRect()
paper.clientToLocalRect(rect)
Transform the rectangle rect
defined in the client coordinate system to the local coordinate system.
var bcr = paper.svg.getBoundingClientRect();
var localRect1 = paper.clientToLocalRect({ x: bcr.left, y: bcr.top, width: bcr.width, height: bcr.height });
// alternative method signature
var localRect2 = paper.clientToLocalRect(bcr.left, bcr.top, bcr.width, bcr.height);
// Move the element to the center of the paper viewport.
var localCenter = localRect1.center();
var elSize = element.size();
element.position(localCenter.x - elSize.width, localCenter.y - elSize.height);
defineFilter()
paper.defineFilter(filterDefinition)
Define an SVG filter for later reuse within the paper. The method returns the filter id and the filterDefinition
must have the following form:
{
name: <name of the filter>,
args: <filter arguments>
}
Where name
is the name of the filter. See below for the list of built-in filters. args
is an object containing filter parameters. These parameters are dependent on the filter used and are described in the list below as well. Example usage:
var filterId = paper.defineFilter({
name: 'dropShadow',
args: {
dx: 2,
dy: 2,
blur: 3
}
});
svgNode.setAttribute('filter', `url(#${filterId})`);
The following is the list of built-in filters. All these filters are defined in the joint.util.filter
namespace. This namespace can be extended simply by adding a new method to it with one argument, an object with filter parameters, returning a string representing the SVG filter definition.
blur
x
- horizontal blury
- vertical blur [optional, if not definedy
is the same asx
]
dropShadow
dx
- horizontal shiftdy
- vertical shiftblur
- blurcolor
- coloropacity
- opacity
grayscale
amount
- the proportion of the conversion.1
is completely grayscale.0
leaves the element unchanged.
sepia
amount
- the proportion of the conversion.1
is completely sepia.0
leaves the element unchanged.
saturate
amount
- the proportion of the conversion.0
is completely un-saturated.1
leaves the element unchanged.
hueRotate
angle
- the number of degrees around the color circle the input samples will be adjusted
invert
amount
- the proportion of the conversion.1
is completely inverted.0
leaves the element unchanged.
brightness
amount
- the proportion of the conversion.0
makes the element completely black.1
leaves the element unchanged.
contrast
amount
- the proportion of the conversion.0
makes the element completely black.1
leaves the element unchanged.
defineGradient()
paper.defineGradient(gradientDefinition)
Define an SVG gradient for later reuse within the paper. The method returns the gradient id and the gradientDefinition
must be an object with the following properties:
Name | Type | Description |
---|---|---|
type | 'linearGradient' | 'radialGradient' |
id | string | (optional) - A unique identifier of the gradient. The id is generated if none provided. |
attrs | object | (optional) - Additional SVG attributes for the SVGGradientElement. |
stops | array | An array of stops. |
Where a stop
is an object with the following properties:
Name | Type | Description |
---|---|---|
color | string | Indicates what color to use at that gradient stop. |
offset | number | string |
opacity | number | (optional) - A number in the [0..1] range representing the transparency of the stop color. |
const gradientId = paper.defineGradient({
type: 'linearGradient',
stops: [
{ offset: '0%', color: '#E67E22' },
{ offset: '20%', color: '#D35400' },
{ offset: '40%', color: '#E74C3C' },
{ offset: '60%', color: '#C0392B' },
{ offset: '80%', color: '#F39C12' }
]
});
svgNode.setAttribute('fill', `url(#${gradientId})`);
For an introduction to gradients, please refer to the tutorial on Filters and Gradients.
defineMarker()
paper.defineMarker(markerDefinition)
Define an SVG marker for later reuse within the paper. The method returns the marker id. The markerDefinition
parameter can be an object with the following properties:
Name | Type | Description |
---|---|---|
id | string | (optional) - A unique identifier of the marker. The id is generated if none provided. |
attrs | object | (optional) - Additional SVG attributes for the SVGMarkerElement. |
markup | string |