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Β | Β array |
The coordinate system for defining path data within marker
is as follows:
Point (x,y ) | Relative position |
---|---|
0,0 | At marker-start , marker-end or marker-mid point, as appropriate. |
n,0 | If n > 0 , position along path direction (i.e. start -> end). |
If n < 0 , position opposite to path direction (i.e. start <- end). | |
0,m | If m > 0 , position to the right of path direction. |
If m < 0 , position to the left of path direction. |
An example of JSON markup with id
specified:
paper.defineMarker({
id: 'my-marker',
markup: [{
tagName: 'circle',
attributes: {
'cx': '6',
'cy': '0',
'r': '12',
'fill': '#7b5cce'
}
}, {
tagName: 'polygon',
attributes: {
'points': '0,0 6,6 12,0 6,-6',
'fill': '#d63865',
'stroke': '#fff'
}
}]
});
// Draw the shape at the start of a path
svgPathNode.setAttribute('marker-start', `url(#my-marker)`);
The same example in string markup:
paper.defineMarker({
id: 'my-marker',
markup: `
<circle cx="6" cy="0" r="12" fill="#7b5cce" />
<polygon points="0,0 6,6 12,0 6,-6" fill="#d63865" stroke="#fff" />
`
});
// Draw the shape at the end of a path
svgPathNode.setAttribute('marker-start', `url(#my-marker)`);
Alternatively, defining a marker is possible via a flat object with the following properties:
Name | Type | Description |
---|---|---|
id | string | (optional) - A unique identifier of the marker. The id is generated if none provided. |
type | string | (optional) - The type of the SVGElement to generate to represent the marker ('path' , 'circle' , 'ellipse' , 'rect' , 'polyline' and 'polygon' ). Default is 'path' . |
[SVGAttribute] | any | (optional) - A presentation SVG attribute (e.g fill: 'red' ) to be applied on the generated SVGElement (see type ). |
The coordinate system for defining path data is the same as above.
An example of specifying marker content via a flat object and referring to it in code via its automatically-generated id
:
const markerId = paper.defineMarker({
type: 'path', // SVG Path
fill: '#666',
stroke: '#333',
d: 'M 10 -10 0 0 10 10 Z'
});
// Draw an arrow at the start and the end of a path
svgPathNode.setAttribute('marker-start', `url(#${markerId})`);
svgPathNode.setAttribute('marker-end', `url(#${markerId})`);
definePattern()β
paper.definePattern(patternDefinition)
Define an SVG pattern for later reuse within the paper. The method returns the pattern id and the patternDefinition
must be an object with the following properties:
Name | Type | Description |
---|---|---|
id | string | (optional) - A unique identifier of the pattern. The id is generated if none provided. |
attrs | object | (optional) - Additional SVG attributes for the SVGGradientElement. |
markup | string | array |
const patternId = paper.definePattern({
attrs: {
width: 10,
height: 10
},
markup: [{
tagName: 'polygon',
attributes: {
points: '0,0 2,5 0,10 5,8 10,10 8,5 10,0 5,2'
}
}]
});
svgNode.setAttribute('fill', `url(#${patternId})`);
drawBackground()β
paper.drawBackground(opt);
Sets the paper background defined by the opt
object. Please see the background paper option for available configuration.
dumpViews()β
paper.dumpViews([opt])
Add all paper views into the DOM and update them to make sure that the views reflect the cells' models.
An extra argument may be provided in the opt
object:
viewportβ
viewport: Function
Callback function to determine whether a given view should be added to the DOM. By default, paper.options.viewport
is used, but you may provide a different callback function. The format of the callback method is described in the option's documentation, as are examples of usage.
findView()β
paper.findView(element)
Find a view (instance of joint.dia.ElementView
or joint.dia.LinkView
) associated with a DOM element in the paper. element
can either be a DOM element, or a CSS selector. Sometimes, it is useful to find a view object for an element in the DOM. This method finds the closest view for any subelement of a view element.
findViewByModel()β
paper.findViewByModel(model)
Find a view (instance of joint.dia.ElementView
or joint.dia.LinkView
) associated with a model. model
can either be an instance of joint.dia.Element
or joint.dia.Link
.
findViewsFromPoint()β
paper.findViewsFromPoint(point)
Find views (instance of joint.dia.ElementView
) under a certain point in the paper. point
is an object with x
and y
properties. Returns an array of views whose bounding box contains point
. Note that there can be more then one views as views might overlap. Note there is a difference between this method and the joint.dia.Graph:findModelsFromPoint. A bounding box of a view can be different than the area computed by an element model position
and size
. For example, if a <text>
SVG element in the shape is positioned relatively and shifted down below the normal shape area (e.g. using the JointJS special attributes), the bounding box of the view will be bigger than that of the model.
findViewsInArea()β
paper.findViewsInArea(rect [, opt])
Find views (instance of joint.dia.ElementView
) in a certain area in the paper. rect
is an object with x
, y
, width
and height
properties. Return an array of views whose bounding box intersects the rect
rectangle.
If opt.strict
is true
, return an array of views whose bounding box is contained within the rect
rectangle (i.e. not only intersects it).
fitToContent()β
paper.fitToContent([opt])
Expand or shrink the paper to fit the content inside it. The method returns the area (g.Rect
) of the paper after fitting in local coordinates.
The list of all available options can be found in the documentation of the paper.getFitToContentArea
function. You can try many of these options interactively in the paper demo (Fit to content
).
This method might internally trigger the "resize"
and "translate"
events. These can be handled by listening on the paper object (paper.on('resize', myHandler)
).
paper.fitToContent([gridWidth, gridHeight, padding, opt])
Deprecated usage. All parameters are expected to be passed inside the opt
object.
freeze()β
paper.freeze()
Freeze an async
paper. In this state, the paper does not automatically re-render upon changes in the graph. This is useful when adding large numbers of cells.
Use paper.unfreeze()
to take the paper back out of the frozen state and to reflect the changes made in the graph in the meantime (if any).
getArea()β
paper.getArea()
Return a rectangle representing the area of the paper, in local units (without transformations).
Creates a rectangle object with { x: 0, y: 0 }
and with width
and height
values according to the paper.getComputedSize()
function. Then uses the paper.paperToLocalRect()
function to transform that rectangle into local units.
getComputedSize()β
paper.getComputedSize()
Return an object containing width
and height
properties. It resolves any computation these property values may contain (e.g resolves "100%"
to the actual client width).
getContentArea()β
paper.getContentArea()
Return a rectangle representing the area occupied by paper content, in local units (without transformations).
If opt.useModelGeometry
is set (default is false
), occupied area is calculated from the dimensions of component cells' models (not views). This option is useful whenever one or more of the paper cells are not in the DOM (e.g. during asynchronous calls). However, the method uses a simplified heuristic that is different from the one used by the browser; the mapping between dimensions of cell views and dimensions of cells models is not necessarily one-to-one. (Most notably, ports are not included in model-reported occupied areas. In addition, the area occupied by links is constructed from link vertices, which may exclude portions of protruding Curveto and Arcto segments.)
getContentBBox()β
paper.getContentBBox(opt)
Return the bounding box of the content inside the paper, in client units (as it appears on the screen).
If opt.useModelGeometry
is set (default is false
), the bounding box is calculated from the dimensions of component cells' models (not views). This option is useful whenever one or more of the paper cells are not in the DOM (e.g. during asynchronous calls). However, the method uses a simplified heuristic that is different from the one used by the browser; the mapping between dimensions of cell views and dimensions of cells models is not necessarily one-to-one. (Most notably, ports are not included in model-reported bounding boxes. In addition, the bounding boxes of links are constructed from link vertices, which may exclude portions of protruding Curveto and Arcto segments.)
getFitToContentArea()β
paper.getFitToContentArea([opt])
Return the bounding box in the local coordinate system based on the position and size of the current content and options provided.
The function accepts an object with the following options:
-
opt.gridWidth
andopt.gridHeight
β snap the resulting width and height of the paper to a grid defined by these dimensions. -
opt.padding
β additional padding around the resulting paper. It may be specified as a number, in which case it represents the padding width on all sides of the paper. It may be an object of the form{ top?: [number], right?: [number], bottom?: [number], left?: [number], vertical?: [number], horizontal?: [number] }
. -
opt.allowNewOrigin
β should the origin of the resulting paper be adjusted to match the origin of the paper content? In addition to a falsy value being set, three values are recognized by this option:'positive'
,'negative'
,'any'
.false
- by default, the method only recognizes the content at positive coordinates and puts the origin of resulting paper at the original point(0,0)
.'positive'
β the method only recognizes the content at positive coordinates and puts the origin of resulting paper at the origin of the content. (Still, if the content starts at negative coordinates in an axis, the resulting paper's origin will be assigned0
in that axis.)'negative'
β the method only recognizes the content at negative coordinates and puts the origin of resulting paper at the origin of the content. (However, if the content starts at positive coordinates in an axis, the resulting paper's origin will be assigned0
in that axis.)'any'
β the method recognizes all of the paper content. The origin of the resulting paper will be at the origin of the content.
-
opt.allowNegativeBottomRight
- can the bottom-right corner of the resulting paper have negative coordinates? By default, the paper area always contains point (0,0). i.e.false
.// Resize the paper to match the tight bounding box of the content regardless of its position.
paper.fitToContent({
allowNewOrigin: 'any',
allowNegativeBottomRight: true
}); -
opt.minWidth
andopt.minHeight
β define the minimum width and height of the resulting paper after fitting it to content. -
opt.maxWidth
andopt.maxHeight
β define the maximum width and height of the resulting paper after fitting it to content. -
opt.useModelGeometry
β should paper content area be calculated from cell models instead of views? The default isfalse
. See the documentation of thepaper.getContentArea
function for more details. -
opt.contentArea
β an object of the form{ x: [number], y: [number], width: [number], height: [number] }
is the area representing the content bounding box in the local coordinate system that paper should be fitted to. By defaultopt.contentArea
ispaper.getContentArea(opt)
.
hasScheduledUpdates()β
paper.hasScheduledUpdates()
Return true
if any changes were made to the graph which are not yet reflected in the paper. (Call the updateViews
function to update these views.) Return false
otherwise.
hideTools()β
paper.hideTools()
Hide all tools attached to all element and link views on this paper.
isDefined()β
paper.isDefined(graphicalObjectId)
Return true
if there is a graphical object (gradient, filter, marker) with graphicalObjectId
already defined within the paper. Return false
otherwise.
isFrozen()β
paper.isFrozen()
Return true
if the paper is currently frozen
. Return false
otherwise.
localToClientPoint()β
paper.localToClientPoint(p)
Transform the point p
defined in the local coordinate system to the client coordinate system.
var rightMidPoint = element.getBBox().rightMiddle();
var clientPoint1 = paper.localToClientPoint(rightMidPoint);
// alternative method signature
var clientPoint2 = paper.localToClientPoint(rightMidPoint.x, rightMidPoint.y);
// Draw an HTML rectangle next to the element.
var div = document.createElement('div');
div.style.position = 'fixed';
div.style.background = 'red';
div.style.left = clientPoint1.x + 'px';
div.style.top = clientPoint1.y + 'px';
div.style.width = '40px';
div.style.height = '40px';
div.style.marginLeft = '10px';
div.style.marginTop = '-20px';
document.body.appendChild(div);
localToClientRect()β
paper.localToClientRect(rect)
Transform the rectangle rect
defined in local coordinate system to the client coordinate system.
var bbox = element.getBBox();
var clientRect1 = paper.localToClientRect(bbox);
// alternative method signature
var clientRect2 = paper.localToClientRect(bbox.x, bbox.y, bbox.width, bbox.height);
// Draw an HTML rectangle above the element.
var div = document.createElement('div');
div.style.position = 'fixed';
div.style.background = 'red';
div.style.left = clientRect1.x + 'px';
div.style.top = clientRect1.y + 'px';
div.style.width = clientRect1.width + 'px';
div.style.height = clientRect1.height + 'px';
paper.el.appendChild(div);
localToPagePoint()β
paper.localToPagePoint(p)
Transform the point p
defined in the local coordinate system to the page coordinate system.
var rightMidPoint = element.getBBox().rightMiddle();
var pagePoint1 = paper.localToPagePoint(rightMidPoint);
// alternative method signature
var pagePoint2 = paper.localToPagePoint(rightMidPoint.x, rightMidPoint.y);
// Draw an HTML rectangle next to the element.
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.background = 'red';
div.style.left = pagePoint1.x + 'px';
div.style.top = pagePoint1.y + 'px';
div.style.width = '40px';
div.style.height = '40px';
div.style.marginLeft = '10px';
div.style.marginTop = '-20px';
document.body.appendChild(div);
localToPageRect()β
paper.localToPageRect(rect)
Transform the rectangle rect
defined in local coordinate system to the page coordinate system.
var bbox = element.getBBox();
var pageRect1 = paper.localToPageRect(bbox);
// alternative method signature
var pageRect2 = paper.localToPageRect(bbox.x, bbox.y, bbox.width, bbox.height);
// Draw an HTML rectangle above the element.
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.background = 'red';
div.style.left = pageRect1.x + 'px';
div.style.top = pageRect1.y + 'px';
div.style.width = pageRect1.width + 'px';
div.style.height = pageRect1.height + 'px';
document.body.appendChild(div);
localToPaperPoint()β
paper.localToPaperPoint(p)
Transform the point p
defined in the local coordinate system to the paper coordinate system.
var rightMidPoint = element.getBBox().rightMiddle();
var paperPoint1 = paper.localToPaperPoint(rightMidPoint);
// alternative method signature
var paperPoint2 = paper.localToPaperPoint(rightMidPoint.x, rightMidPoint.y);
// Draw an HTML rectangle next to the element.
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.background = 'red';
div.style.left = paperPoint1.x + 'px';
div.style.top = paperPoint1.y + 'px';
div.style.width = '40px';
div.style.height = '40px';
div.style.marginLeft = '10px';
div.style.marginTop = '-20px';
paper.el.appendChild(div);
localToPaperRect()β
paper.localToPaperRect(rect)
Transform the rectangle rect
defined in the local coordinate system to the paper coordinate system.
var bbox = element.getBBox();
var paperRect1 = paper.localToPaperRect(bbox);
// alternative method signature
var paperRect2 = paper.localToPaperRect(bbox.x, bbox.y, bbox.width, bbox.height);
// Draw an HTML rectangle above the element.
var div = document.createElement('div');
div.style.position = 'absolute';
div.style.background = 'red';
div.style.left = paperRect1.x + 'px';
div.style.top = paperRect1.y + 'px';
div.style.width = paperRect1.width + 'px';
div.style.height = paperRect1.height + 'px';
paper.el.appendChild(div);
matrix()β
paper.matrix()
When called with no parameter, the method returns the current transformation matrix (instance of SVGMatrix) of the paper.
const { a: sx, b: sy, e: tx, f: ty } = paper.matrix();
paper.matrix(SVGMatrix, [data])
It sets the new viewport transformation based on the SVGMatrix
otherwise.
paper.matrix({ a: 2, b: 0, c: 0, d: 2, e: 0, f: 0 }); // scale the paper twice
paper.matrix(V.createSVGMatrix().translate(100, 100)); // translate the paper by 100, 100
When a new transformation is set the following events (in this order) are triggered.
"scale"
event with the new scale and thedata
object if it was specified when the method was called."translate"
event with the new translation and thedata
object if it was specified when the method was called."transform"
event with the new transformation matrix and thedata
object if it was specified when the method was called.
paper.on('scale', (sx, sy, data) => console.log(sx, sy, data.foo));
paper.on('translate', (tx, ty, data) => console.log(tx, ty, data.foo));
paper.on('transform', (matrix, data) => console.log(matrix, data.foo));
paper.matrix({ a: 2, b: 0, c: 0, d: 2, e: 10, f: 10 }, { foo: 'bar' }); // will trigger all events
pageOffset()β
paper.pageOffset()
Returns coordinates of the paper viewport, relative to the document.
pageToLocalPoint()β
paper.pageToLocalPoint(p)
Transform the point p
defined in the page coordinate system to the local coordinate system.
paper.on('blank:pointerup', function(evt) {
var pagePoint = g.Point(evt.pageX, evt.pageY);
var localPoint1 = this.pageToLocalPoint(pagePoint);
// alternative method signature
var localPoint2 = this.pageToLocalPoint(evt.pageX, evt.pageY);
// Move the element to the point, where the user just clicks.
element.position(localPoint1.x, localPoint1.y);
});
pageToLocalRect()β
paper.pageToLocalRect(rect)
Transform the rectangle rect
defined in the page coordinate system to the local coordinate system.
var x, y;
paper.on('blank:pointerdown', function(evt) {
x = evt.pageX;
y = evt.pageY;
});
paper.on('blank:pointerup', function(evt) {
var pageRect = g.Rect(x, y, evt.pageX - x, evt.pageY - y).normalize();
var localRect1 = this.pageToLocalRect(pageRect);
// alternative method signature
var localRect2 = this.pageToLocalRect(x, y, evt.pageX - x, evt.pageY - y).normalize();
// Move and resize the element to cover the area, that the user just selected.
element.position(localRect1.x, localRect1.y);
element.resize(localRect1.width, localRect1.height);
});
paperToLocalPoint()β
paper.paperToLocalPoint(p)
Transform the point p
defined in the paper coordinate system to the local coordinate system.
var paperCenter = g.Point(paper.options.width / 2, paper.options.height / 2);
var localPoint1 = paper.paperToLocalPoint(paperCenter);
// alternative method signature
var localPoint2 = paper.paperToLocalPoint(paper.options.width / 2, paper.options.height / 2);
// Move the element to the center of the paper viewport.
var elSize = element.size();
element.position(localPoint1.x - elSize.width, localPoint1.y - elSize.height);
paperToLocalRect()β
paper.paperToLocalRect(rect)
Transform the rectangle rect
defined in the paper coordinate system to the local coordinate system.
var paperRect = g.Rect(0, 0, paper.options.width, paper.options.height);
var localRect1 = paper.paperToLocalRect(paperRect);
// alternative method signature
var localRect2 = paper.paperToLocalRect(0, 0, paper.options.width, paper.options.height);
// Move and resize the element to cover the entire paper viewport.
element.position(localRect1.x , localRect1.y);
element.size(localRect1.width, localRect1.height);
removeTools()β
paper.removeTools()
Remove all tools view objects attached to all element and link views on this paper.
requireView()β
paper.requireView(cell[, opt])
Ensure that the view associated with the cell
model is attached to the DOM and that it is updated.
This function finds the view by the cell model. If the view is not part of the paper's DOM (e.g. because it was outside the paper viewport), this function attaches it. Additionally, the view is updated to reflect any changes that may have been done on the cell model in the meantime.
Certain CellView methods require the view to be updated and present in the DOM to function properly
(e.g. elementView.getBBox
/linkView.getBBox). In async
papers, you should precede calls to these
methods with this function to guard against inconsistencies.
If opt.silent
is set to true
, the paper beforeRender and afterRender callbacks are not fired (and 'render:done'
event is not triggered).
scale()β
paper.scale()
If the method is called with no parameter the current paper scale
transformation is returned.
paper.scale() // returns e.g. { sx: 2, sy: 2 }
paper.scale(sx, [sy, data])
Lets you modify the scale of a paper.
paper.scale(2) // scale 2x (uniformly)
paper.scale(2,3) // scale 2x in `x` axis 3x in `y` axis (non-uniformly)
If the method is called the "scale"
and "transform"
events are triggered on the paper (only if the new scale differs from the previous).
The event handlers receive the current scale / matrix and the data
object if it was specified when the method was called.
paper.on('scale', (sx, sy, data) => console.log(sx, sy, data.foo));
paper.on('transform', (matrix, data) => console.log(matrix, data.foo));
paper.scale(2, 2, { foo: 'bar' }); // will trigger both events
scaleContentToFit()β
paper.scaleContentToFit([opt])
Deprecated. Use paper.transformToFitContent()
instead.
Scale the paper content so that it fits the paper dimensions.
scaleUniformAtPoint()β
paper.scaleUniformAtPoint(scale, point, [data])
Lets you modify the transformation of a paper, so that the paper is scaled uniformly around the given point.
// scale 2x around the point (100, 100)
paper.scaleUniformAtPoint(2, { x: 100, y: 100 });
When the method is called, a couple of transformation events (e.g. "transform"
event) might be triggered. For more details, please see the matrix() method.
The method is ideal for zooming in/out around the mouse pointer.
paper.on('paper:pinch', function(evt, x, y, sx) {
evt.preventDefault();
const { sx: sx0 } = paper.scale();
paper.scaleUniformAtPoint(sx0 * sx, { x, y });
});
paper.on('paper:pan', function(evt, tx, ty) {
evt.preventDefault();
evt.stopPropagation();
const { tx: tx0, ty: ty0 } = paper.translate();
paper.translate(tx0 - tx, ty0 - ty);
});
setDimensions()β
paper.setDimensions(width, height, [data])
Change dimensions of a paper. Dimensions should always be passed to the options object of the joint.dia.Paper
constructor. Use setDimensions()
to change dimensions of the paper later on if needed.
Type | Description |
---|---|
Number | Dimension in pixels (e.g 800 ). |
String | Dimension as CSS property value (e.g
|
null | No dimension set. Useful when size of the paper controlled in CSS. |
If new dimensions are set, the "resize"
event is triggered (only if the size has changed). The event handler receives the current size and the data
object if it was specified when the method was called.
paper.on('resize', (width, height, data) => console.log(width, height, data.foo));
paper.setDimensions(800, 600, { foo: 'bar' }); // will trigger the event
setGrid()β
paper.setGrid(gridOption)
Set the type of visual grid on the paper. If a falsy value is provided, the grid is removed.
paper.setGrid(); // removes the grid visual
paper.setGrid(true); // default pattern (dot) with default settings
paper.setGrid('mesh'); // pre-defined pattern with default settings
paper.setGrid({ name: 'dot', args: { color: 'hsla(212, 7%, 75%, 0.5)' }});
setGridSize()β
paper.setGridSize(gridSize)
Set the grid size of the paper.
setInteractivity()β
paper.setInteractivity(interactive)
Set the interactivity of the paper. For example, to disable interactivity:
paper.setInteractivity(false);
showTools()β
paper.showTools()
Show all tools attached to all element and link views on this paper.
transformToFitContent()β
paper.transformToFitContent([opt])
Transforms the paper so that it fits the content.
The function accepts an object with additional settings (all optional):
opt.padding
β a number or an object of the form{ top?: [number], right?: [number], bottom?: [number], left?: [number], vertical?: [number], horizontal?: [number] }
that specifies the width of additional padding that should be added around the resulting (scaled) paper content. Default is0
.opt.preserveAspectRatio
β should the original aspect ratio of the paper content be preserved in the scaled version? Default istrue
.opt.minScaleX
,opt.minScaleY
,opt.maxScaleX
,opt.maxScaleY
β the minimum and maximum allowed scale factors for both axes.opt.scaleGrid
β a number to be used as a rounding factor for the resulting scale. For example, if you pass0.2
to this option and the scale factor is calculated as1.15
, then the resulting scale factor will be rounded to1.2
.opt.useModelGeometry
β should paper content bounding box be calculated from cell models instead of views? Default isfalse
. See the documentation of thepaper.getContentBBox
function for more details.opt.fittingBBox
β an object of the form{ x: [number], y: [number], width: [number], height: [number] }
is the area of the paper that the content should be scaled to. By defaultopt.fittingBBox
is{ x: 0, y: 0, width: paper.options.width, height: paper.options.height }
, i.e. the bounding box of the paper in the paper coordinate system.opt.contentArea
β an object of the form{ x: [number], y: [number], width: [number], height: [number] }
is the area representing the content in local coordinate system that should be scaled to fit theopt.fittingBBox
. By defaultopt.contentArea
ispaper.getContentArea(opt)
.opt.verticalAlign
β a string which specifies how the content should be vertically aligned in the transformed paper. The options are'top'
,'middle'
and'bottom'
. By default theopt.verticalAlign
is'top'
.opt.horizontalAlign
β a string which specifies how the content should be horizontally aligned in the transformed paper. The options are'left'
,'middle'
and'right'
. By default theopt.horizontalAlign
is'left'
.
The function is illustrated in our paper demo (Scale content to fit
).
translate()β
paper.translate()
If the method is called with no parameter the current paper translate
transformation is returned.
paper.translate() // returns e.g. { tx: 100, ty: 100 }
paper.translate(x, y, [data])
Lets you modify the origin (zero coordinates) of a paper.
paper.translate(100, 200) // set the origin to `x=100` and `y=200`
paper.translate(100) // same as calling `translate(100,0)`
If the method is called the "translate"
and "transform"
events are triggered on the paper (only if the origin has changed). The event handlers receive the current translation / matrix and the data
object if it was specified when the method was called.
paper.on('translate', (tx, ty, data) => console.log(tx, ty, data.foo));
paper.on('transform', (matrix, data) => console.log(matrix, data.foo));
paper.translate(100, 200, { foo: 'bar' }); // will trigger both events
unfreeze()β
paper.unfreeze([opt])
Update the views of an async
paper to make sure that the views reflect the cells' models; unfreeze the paper afterward.
Several extra arguments may be provided in the opt
object:
batchSizeβ
batchSize: number
For async
papers, how many views should there be per one asynchronous process? Default is 1000
.
progressβ
progress: Function
Callback function that is called whenever a batch is finished processing. The callback function is provided with three arguments:
done | boolean | Are we done? Was this the last batch? |
processed | number | How far along are we? How many elements have been processed as part of a batch so far? |
total | number | How many views are there? How many elements in will have been processed as part of a batch when we are done? |
viewportβ
viewport: Function
Callback function to determine whether a given view should be added to the DOM. By default, paper.options.viewport
is used,
but you may provide a different callback function. The format of the callback method is described in the option's documentation, as are examples of usage.
beforeRenderβ
beforeRender: Function
Callback function executed before processing scheduled updates. By default, paper.options.beforeRender
is used, but
you may provide a different callback function. The format of the callback method is described in the option's documentation.
afterRenderβ
afterRender: Function
Callback function executed after all scheduled updates had been processed. By default, paper.options.afterRender
is used,
but you may provide a different callback function. The format of the callback method is described in the option's documentation.
Use paper.freeze()
to freeze the paper again.
updateViews()β
paper.updateViews([opt])
Update views in a frozen async
paper to make sure that the views reflect the cells' models; keep the paper frozen afterwards.
An extra argument may be provided in the opt
object:
viewportβ
viewport: Function
Callback function to determine whether a given view should be added to the DOM. By default, paper.options.viewport
is used, but you may provide a different callback function. The format of the callback method is described in the option's documentation,
as are examples of usage.
Propertiesβ
The Paper object exposes several properties. Normally, you do not need to access these properties, but they may prove handy in some (advanced) situations:
cellsβ
The cells layer - a reference to the SVG group <g>
element the paper wraps all the rendered elements and links into.
defsβ
A reference to the SVG <defs>
element used to define SVG elements for later reuse. This is also a good place to put SVG masks, patterns, filters and gradients.
layersβ
A reference to the SVG group <g>
element that contains all the layers of the paper. Paper transformations such as scale is performed on this element and it affects all the layers inside.
svgβ
A reference to the SVG document object the paper uses to render all the graphics.
toolsβ
The tools layer - a reference to the SVG group <g>
element the paper wraps all the rendered tools into.
Eventsβ
The following list contains events that you can react on in a paper:
connectβ
The callback function is passed linkView
, evt
, elementViewConnected
, magnet
and arrowhead
as arguments.
link:connect | Triggered when a link is connected to a cell. The event is triggered after the user reconnects a link. |
---|---|
link:snap:connect | Triggered when a link is connected to a cell. The event (or multiple events) can be triggered while the user is reconnecting a link and snapLinks option is enabled. |
contextmenuβ
Triggered when pointer is right-clicked on a target. This trigger is fired on a mousedown
event and it does not depend on different implementations of the contextmenu
event.
The callback function is passed cellView
, evt
, x
and y
as arguments.
cell:contextmenu | Triggered when pointer is right-clicked on a cell. |
---|---|
element:contextmenu | Triggered when pointer is right-clicked on an element. |
link:contextmenu | Triggered when pointer is right-clicked on a link. |
blank:contextmenu | Triggered when pointer is right-clicked on the paper outside any cell. The callback function is passed evt , x and y as arguments. |
disconnectβ
The callback function is passed linkView
, evt
, elementViewDisconnected
, magnet
and arrowhead
as arguments.
link:disconnect | Triggered when a link is disconnected from a cell. The event is triggered after the user reconnects a link. |
---|---|
link:snap:disconnect | Triggered when a link is disconnected from a cell. The event (or multiple events) can be triggered while the user is reconnecting a link and snapLinks option is enabled. |
highlightβ
cell:highlight | Triggered when the The callback function is invoked with the following arguments:
|
---|---|
cell:highlight:invalid | Triggered when a highlighter makes an attempt to highlight a node, that doesn't exist on the CellView (e.g. a port was highlighted and now it is removed). The callback function is passed
|
magnetβ
Triggered when interacting with a magnet target.
The callback function is passed elementView
, evt
, magnetSVGElement
, x
, y
as arguments.
element:magnet:contextmenu | Triggered when pointer is right-clicked on an element magnet. Calling |
---|---|
element:magnet:pointerclick | Triggered when pointer is clicked on an element magnet and no link was created yet from this magnet
(controlled by magnetThreshold option). Calling |
element:magnet:pointerdblclick | Triggered when pointer is double-clicked on an element magnet. Calling |
element:magnet:pointerdown | Triggered when pointer is pressed down on a magnet element. |
element:magnet:pointermove | Triggered when pointer is moved after pointerdown on the magnet element. |
element:magnet:pointerup | Triggered when pointer is released after pointerdown on the magnet element. |
mouseenterβ
Triggered when pointer enters the area above a target.
The callback function is passed cellView
and evt
as arguments.
cell:mouseenter | Triggered when pointer enters the area above a cell. |
---|---|
element:mouseenter | Triggered when pointer enters the area above an element. |
link:mouseenter | Triggered when pointer enters the area above a link. |
paper:mouseenter | Triggered when pointer enters the area of the paper (including paper border, if present). The callback function is passed evt as argument. |
mouseleaveβ
Triggered when pointer leaves the area above a target.
The callback function is passed cellView
and evt
as arguments.
cell:mouseleave | Triggered when pointer leaves the area above a cell. |
---|---|
element:mouseleave | Triggered when pointer leaves the area above an element. |
link:mouseleave | Triggered when pointer leaves the area above a link. |
paper:mouseleave | Triggered when pointer leaves the area of the paper (including paper border, if present). The callback function is passed evt as argument. |
mouseoutβ
Triggered when pointer ceases to hover directly over a target.
The callback function is passed cellView
and evt
as arguments.
cell:mouseout | Triggered when pointer ceases to hover directly over a cell. |
---|---|
element:mouseout | Triggered when pointer ceases to hover directly over an element. |
link:mouseout | Triggered when pointer ceases to hover directly over a link. |
blank:mouseout | Triggered when pointer ceases to hover over the svg element of the paper outside any cell.The callback function is passed evt as argument. |
mouseoverβ
Triggered when pointer begins to hover directly over a target.
The callback function is passed cellView
and evt
as arguments.
cell:mouseover | Triggered when pointer begins to hover directly over a cell. |
---|---|
element:mouseover | Triggered when pointer begins to hover directly over an element. |
link:mouseover | Triggered when pointer begins to hover directly over a link. |
blank:mouseover | Triggered when pointer begins to hover over the svg element of the paper outside any cell.The callback function is passed evt as argument. |
mousewheelβ
Triggered when mouse wheel is rotated while pointer is on a target.
The callback function is passed cellView
, evt
, x
, y
and delta
as arguments.
cell:mousewheel | Triggered when mouse wheel is rotated while the pointer is on a cell. |
---|---|
element:mousewheel | Triggered when mouse wheel is rotated while the pointer is on an element. |
link:mousewheel | Triggered when mouse wheel is rotated while the pointer is on a link. |
blank:mousewheel | Triggered when mouse wheel is rotated while the pointer is on the paper outside any cell. The callback function is passed evt , x , y and delta as arguments. |
panβ
Triggered when a pan event is emitted while the pointer is on top of the target. Pan events are similar to mousewheel events, but while mousewheel events cover only the Y axis, pan events cover both X and Y axis. This is usually possible with touchpads / trackpad devices.
The callback function is passed evt
, deltaX
and deltaY
as arguments.
paper:pan | Triggered when a pan event is emitted while the pointer is on the paper or any cell. |
---|
pinchβ
Triggered when a pinch event is emitted while the pointer is on top of the target. This is usually possible with touchpads / trackpad devices.
The callback function is passed evt
, x
, y
and scale
as arguments.
paper:pinch | Triggered when a pinch event is emitted while the pointer is on the paper or any cell. |
---|
pointerclickβ
Triggered when pointer is left-clicked on a target without pointer movement (a click
or touchend
event is detected). Occurs alongside pointerdown
and pointerup
events.
The callback function is passed cellView
, evt
, x
and y
as arguments.
cell:pointerclick | Triggered when pointer is clicked on a cell. |
---|---|
element:pointerclick | Triggered when pointer is clicked on an element. |
link:pointerclick | Triggered when pointer is clicked on a link. |
blank:pointerclick | Triggered when pointer is clicked on the paper outside any cell. The callback function is passed evt , x and y as arguments. |
pointerdblclickβ
Triggered when pointer is double-clicked on a target (a dblclick
event is detected).
The callback function is passed cellView
, evt
, x
and y
as arguments.
cell:pointerdblclick | Triggered when pointer is double-clicked on a cell. |
---|---|
element:pointerdblclick | Triggered when pointer is double-clicked on an element. |
link:pointerdblclick | Triggered when pointer is double-clicked on a link. |
blank:pointerdblclick | Triggered when pointer is double-clicked on the paper outside any cell. The callback function is passed evt , x and y as arguments. |
pointerdownβ
Triggered when pointer is pressed down on a target (a mousedown
or touchstart
event is detected). The paper also starts delegating respective pointermove
and pointerup
events (including their touch counterparts; see below).
The callback function is passed cellView
, evt
, x
and y
as arguments.
cell:pointerdown | Triggered when pointer is pressed down on a cell. |
---|---|
element:pointerdown | Triggered when pointer is pressed down on an element. |
link:pointerdown | Triggered when pointer is pressed down on a link. |
blank:pointerdown | Triggered when pointer is pressed down on the paper outside any cell. The callback function is passed evt , x and y as arguments. |
An example of a simple blank:pointerdown
event listener:
paper.on('blank:pointerdown', function(evt, x, y) {
alert('pointerdown on a blank area in the paper.')
})
Consecutive pointerdown
, pointermove
and pointerup
events can share information through the evt.data
object:
// Create a new link by dragging
paper.on({
'blank:pointerdown': function(evt, x, y) {
const link = new joint.shapes.standard.Link();
link.set('source', { x, y });
link.set('target', { x, y });
link.addTo(this.model);
evt.data = { link, x, y };
},
'blank:pointermove': function(evt, x, y) {
evt.data.link.set('target', { x, y });
},
'blank:pointerup': function(evt) {
var target = evt.data.link.get('target');
if (evt.data.x === target.x && evt.data.y === target.y) {
// remove zero-length links
evt.data.link.remove();
}
}
});
pointermoveβ
Triggered when pointer is moved over a target while pressed down (a mousemove
or touchmove
event is detected).
The callback function is passed cellView
, evt
, x
and y
as arguments.
cell:pointermove | Triggered when pointer is moved over a cell. |
---|---|
element:pointermove | Triggered when pointer is moved over an element. |
link:pointermove | Triggered when pointer is moved over a link. |
blank:pointermove | Triggered when pointer is moved over the paper outside any cell. The callback function is passed evt , x and y as arguments. |
pointerupβ
Triggered when pointer is released on a target after being pressed down (a mouseup
or touchend
event is detected).
The callback function is passed cellView
, evt
, x
and y
as arguments.
cell:pointerup | Triggered when pointer is released on a cell. |
---|---|
element:pointerup | Triggered when pointer is released on an element. |
link:pointerup | Triggered when pointer is relased on a link. |
blank:pointerup | Triggered when pointer is released on the paper outside any cell. The callback function is passed evt , x and y as arguments. |
Calling evt.stopPropagation()
prevents triggering a subsequent pointerclick
event.
render:doneβ
Triggered when all scheduled updates are done (i.e. all scheduled batches have finished).
resizeβ
Triggered when the Paper is resized (i.e. its dimensions are changed).
The callback function is passed width
, height
and data
as arguments:
width
andheight
are numbers which contain the new Paper dimensions.data
is an optionaldata
object passed to the triggering function (e.g. thedata
parameter ofsetDimensions()
, or theopt
parameter offitToContent()
).
scaleβ
Triggered when the Paper is scaled (i.e. zoomed in or out).
The callback function is passed a
, d
and data
as arguments:
a
andd
are numbers which contain the new values of the x-scale and y-scale, respectively.data
is an optionaldata
object passed to the triggering function (e.g. thedata
parameter ofscale()
,scaleUniformAtPoint()
,matrix()
, or theopt
parameter oftransformToFitContent()
).
transformβ
Triggered when the Paper is transformed - scaled and/or translated.
The "transform"
event is always triggered after its associated specific event ("scale"
, "translate"
).
If a single transformation includes both scaling and translating, the "scale"
event is triggered first, the "translate"
event is triggered second, and the "transform"
event is triggered third.
The callback function is passed current
and data
as arguments:
current
is the new transformation matrix (instance of SVGMatrix). Seematrix()
for more information.data
is an optionaldata
object passed to the triggering function (e.g. thedata
parameter ofscale()
,translate()
,scaleUniformAtPoint()
,matrix()
, or theopt
parameter offitToContent()
,transformToFitContent()
).
translateβ
Triggered when the Paper is translated (i.e. panned).
If a single transformation includes scaling and translating, the "scale"
event is triggered first, and the "translate"
event is triggered second.
The callback function is passed e
, f
and data
as arguments:
e
andf
are numbers which contain the new values of the x-position and y-position, respectively.data
is an optionaldata
object passed to the triggering function (e.g. thedata
parameter oftranslate()
,scaleUniformAtPoint()
,matrix()
, or theopt
parameter offitToContent()
,transformToFitContent()
).
unhighlightβ
cell:unhighlight | Triggered when the The callback function is invoked with the following arguments:
|
---|
[custom]β
Custom cell event can be triggered on pointerdown with the event
attribute. Calling evt.stopPropagation()
prevents triggering all subsequent events.