Navigating the canvas
The surface component offers a wide range of functionality for assisting your users in navigating around.
Panning
The surface is an 'infinite pan' canvas that does not use scrollbars. To pan the canvas, the user drags using the left mouse button, or, on touch devices, by dragging a single touch.
Panning is normally enabled, but a surface can be initialized with panning disabled by setting enablePan
to false:
import { newInstance } from "@jsplumbtoolkit/browser-ui"
const toolkit = newInstance()
const surface = toolkit.render(someElement, {
"enablePan": false
});
You can also disable a surface entirely via the setMode
method:
surface.setMode(Surface.DISABLED);
Filtering Panning
It's a fairly common use case that there be some set of elements in your canvas on which a drag should not cause a pan to occur. To handle this, the surface has the panFilter
parameter. This is a function from which you should return true if you would like a pan to begin. You must return boolean true from this function in order for panning to be enabled.
{
panFilter:(eventTarget) => {
return someLogic(eventTarget);
}
}
Zooming
The default behaviour of the surface is to support zooming via the mouse wheel, or on touch devices, via pinch to zoom.
Specifying zoom range
The surface can be zoomed within a given range, whose default value is:
[0.05, 3]
meaning the surface can zoom between 5% and 300%. You can set this when you create a surface:
import { newInstance } from "@jsplumbtoolkit/browser-ui"
const toolkit = newInstance()
const surface = toolkit.render(someElement, {
"zoomRange": [
1,
2
]
});
You can also change the zoom range at runtime, via the setZoomRange method
Wheel zoom
import { newInstance } from "@jsplumbtoolkit/browser-ui"
const toolkit = newInstance()
const surface = toolkit.render(someElement, {
"wheel": {
"zoom": false
}
});
zoom defaults to true.
Filtering wheel events
import { newInstance } from "@jsplumbtoolkit/browser-ui"
const toolkit = newInstance()
const surface = toolkit.render(someElement, {
"wheel": {
"filter": ".someElementClass"
}
});
filter is an optional CSS selector representing elements that should not respond to wheel zoom. Defaults to empty.
Wheel zoom meta key
import { newInstance } from "@jsplumbtoolkit/browser-ui"
const toolkit = newInstance()
const surface = toolkit.render(someElement, {
"wheel": {
"useMetaKey": true
}
});
useMetaKey defaults to false. If true, the wheel zoom only fires when Ctrl (or CMD on Mac) is pressed and the wheel is rotated.
Wheel direction
import { newInstance } from "@jsplumbtoolkit/browser-ui"
const toolkit = newInstance()
const surface = toolkit.render(someElement, {
"wheel": {
"reverse": true
}
});
reverse Defaults to false. If true, the zoom direction is reversed: wheel up zooms out, and wheel down zooms in.
Zoom API
There are a few helper methods for zooming exposed on the surface.
When you want to invoke a method on a Surface or a Toolkit instance, you'll need to get a reference at least to the Surface first (you can access the underlying Toolkit via the toolkitInstance
property on a Surface).
How you do that depends on whether you're using Vanilla JsPlumb, or one of our library integrations.
In JsPlumb Vanilla you create a Toolkit instance via the newInstance
method and then a surface by invoking render
on the Toolkit:
import { newInstance } from "@jsplumbtoolkit/browser-ui"
const toolkit = newInstance()
const surface = toolkit.render(someElement, ...);
zoomToFit(options)
Zooms the display so that all tracked elements fit inside the viewport (including invisible nodes). This method will also increase the zoom if necessary in order that the content fills the 90% of the shortest axis of the viewport.
The most basic call you can make is this:
surface.zoomToFit();
zoomToFit
supports a number of parameters:
- fill A decimal indicating how much of the viewport to fill with the zoomed content. Defaults to 0.9.
- padding Padding to leave around all elements. Default is 20 pixels.
- onComplete Optional function to call on operation complete (centering may be animated).
- onStep Optional function to call on operation step (centering may be animated).
- doNotAnimate By default, the centering content step does not use animation (this parameter is set to true). This is due to this method being used most often to initially setup a UI.
- doNotZoomIfVisible Defaults to false. If true, no action is taken if the content is currently all visible.
An example showing the surface animating the content until it fits 80% of the viewport and then popping up an alert:
surface.zoomToFit({
fill:0.8,
doNotAnimate:false,
onComplete:function() { alert("done!"); }
});
To zoom to show only visible nodes, see zoomToVisible.
zoomToFitIfNecessary(options)
Works like zoomToFit
but if all tracked elements are currently visible does not adjust the zoom.
surface.zoomToFitIfNecessary();
All of the parameters supported by zoomToFit
are supported by zoomToFitIfNecessary
.
zoomToBackground(options)
If a background was set, zooms the widget such that the entire background is visible.
surface.zoomToBackground({
onComplete:() => { alert("done!"); }
});
This method also supports onStep
and doNotAnimate
.
zoomToSelection(options)
Zoom to either the current selected set of nodes in the Toolkit (defaults to the current selection filling 90% of the shortest axis in the viewport):
surface.zoomToSelection();
or provide a selection of your own to which to zoom:
surface.zoomToSelection({
fill:0.8,
selection:some Toolkit Selection
});
To find our more about Selections, see here.
This method also supports an optional filter
function, which is used to create a Selection by running it through JsPlumb's filter
method. For instance, this is how you could create what the zoomToVisible
method (described below) does:
surface.zoomToSelection({
filter:(obj) => { return obj.objectType === "Node" && surface.isVisible(obj); }
});
zoomToVisible(options)
Zooms to display all the currently visible nodes. All animation options are supported by this method - it is a wrapper around zoomToSelection
in which we first create a selection representing all the visible nodes.
zoomToVisibleIfNecessary(options)
This method is to zoomToVisible
as zoomToFitIfNecessary
is to zoomToFit
- the content will be centered, but the zoom level will be changed only if all of the currently visible nodes are not visible in the viewport.
setZoom(value)
Sets the current zoom level. This must be a positive decimal number. If it is outside of the current zoom range, it will be clamped to the zoom range.
surface.setZoom(0.5);
Here we have set the zoom to 50%.
nudgeZoom(amount)
Nudges the current zoom level by some value (negative or positive).
// nudge the zoom by 5%
surface.nudgeZoom(0.05);
// nudge the zoom by -15%
surface.nudgeZoom(-0.15);
setZoomRange(range, doNotClamp)
Sets the current zoom range. By default, this method checks if the current zoom is within the new range, and if it is not then setZoom
is called, which will cause the zoom to be clamped to an allowed value in the new range. You can disable this by passing true
for doNotClamp
.
surface.setZoomRange(0.5, 2);
here we have set the zoom range to be 50% minimum, 200% maximum. If the current zoom was outside of this range, it was clamped to be within.
Let's set the zoom to 2, the top of our current range, and then adjust the zoom range without affecting the widget's zoom:
surface.setZoom(2);
surface.setZoomRange([0.5, 1], true);
Clamping Movement
Pan
By default, the surface will clamp movement when panning so that some content is always visible. This can be overridden:
import { newInstance } from "@jsplumbtoolkit/browser-ui"
const toolkit = newInstance()
const surface = toolkit.render(someElement, {
"clamp": false
});
Zoom Movement
It is also default behaviour to clamp the movement of the canvas when the user zooms such that some content is always visible. Without this, it's quite easy for a user to accidentally zoom in such a way that all of the content disappears (consider the case that the canvas is zoomed out a long way and the user then zooms in on some whitespace that is a long way from any content).
As with pan clamping, you can also switch off zoom clamping if you wish:
import { newInstance } from "@jsplumbtoolkit/browser-ui"
const toolkit = newInstance()
const surface = toolkit.render(someElement, {
"clampZoom": false
});
Background
Backgrounds are discussed in a separate page, but a brief mention should be made of the fact that you can also tell the surface to clamp movement such that part of the background is always visible:
import { newInstance } from "@jsplumbtoolkit/browser-ui"
const toolkit = newInstance()
const surface = toolkit.render(someElement, {
"clampToBackground": true
});
Events
Event listeners can be bound to the surface widget in one of three ways:
- via the
bind
method - in the
events
parameter to arender
call on an instance of JsPlumb - in the individual Node, Group, Port and Edge definitions in the
view
parameter to arender
call.
The full list of bindable events is listed on the events page.
In these code examples we're assuming the existence of a reference to a surface. See the note above about how to get a surface reference for the flavour of JsPlumb you are using.
Using bind
surface.bind("canvasClick", (e) => {
console.log("click on the canvas");
});
surface.bind("node:added", (params) => {
});
Declarative binding
You can specify event listeners in the render options for some surface:
{
events:{
canvasClick:(e) => {
console.log("click on the canvas");
},
"node:added":(params) => {}
}
}
Each of the entries in the events
block is equivalent to first instantiating the surface and then calling bind
on it.
Suspending Events
You can suspend/enable events from the surface widget with this method:
surface.setSuspendEvents(true);
You can also wrap the underlying Toolkit's batch
command (which runs a series of operations without making any rendering changes) with the surface widget's batch
command:
surface.batch(() => {
surface.toolkitInstance.addNode({id:"foo"});
surface.toolkitInstance.addNode({id:"bar"});
surface.toolkitInstance.addNode({source:"foo", target:"bar"});
});
This is equivalent to:
surface.setSuspendEvents(true);
surface.toolkitInstance.batch(() => {
surface.toolkitInstance.addNode({id:"foo"});
surface.toolkitInstance.addNode({id:"bar"});
surface.toolkitInstance.addNode({source:"foo", target:"bar"});
});
surface.setSuspendEvents(false);
Selecting vertices
Vertices managed by a surface widget may be "selected" at any point in time programmatically via the associated toolkit instance. When a node is selected, the surface is informed, and its DOM element is assigned the class jtk-surface-selected-element
.
You can also select nodes using the mouse, with a "lasso". To switch into this mode, call setMode
:
surface.setMode(Surface.SELECT);
In order to use the lasso, you need to install the lasso plugin. Checkout the linked page for information about how to configure the lasso.
Exiting Select Mode
Ordinarily, the surface will jump back into pan mode from select mode after some nodes have been selected, but this behaviour can be overridden, using the autoExitSelectMode
flag:
import { newInstance } from "@jsplumbtoolkit/browser-ui"
const toolkit = newInstance()
const surface = toolkit.render(someElement, {
"autoExitSelectMode": false
});
CSS
Miscellaneous
Consuming Right Click
The default behaviour is to consume any right-click events. This is good when your app is in production, and sometimes really annoying when you're in the middle of development. To suppress this behaviour, set consumeRightClick
:
import { newInstance } from "@jsplumbtoolkit/browser-ui"
const toolkit = newInstance()
const surface = toolkit.render(someElement, {
"consumeRightClick": false
});
Direct Rendering
Direct rendering is a mode in which the Surface disables panning, zooming and dragging and automatically adjusts the display so that every node is visible within the viewport. You can use this mode to embed a diagram in a page, and what's super cool about it is that the diagram is "live" - any changes to the dataset will be reflected in the UI.
The diagram is inside a div with a fixed width of 350px and is floated left. Text can flow alongside the diagram. We can also manipulate the contents of the diagram without disrupting the flow of the page - click to add a new node.
Did you click it? Notice how the new node was added and the diagram was adjusted to ensure everything is still visible. If the size of the container changes the diagram will also adapt - to change the width of the container.
In direct render mode JsPlumb will render the contents of the dataset into the container you specify, honouring the dimensions of that container as determined by the page layout.
Setup
Switching on direct rendering requires that you pass a directRender
flag to the parameters used to construct the surface:
import { newInstance } from "@jsplumbtoolkit/browser-ui"
const toolkit = newInstance()
const surface = toolkit.render(someElement, {
"directRender": true
});
The Surface does not disable event handlers when in direct render mode. So if you have mapped any events on specific nodes or edges, or on the canvas itself, these handlers will still be registered.
CSS
A surface in direct render mode will have the css class jtk-surface-direct-render
assigned to the container into which the surface was rendered. The default stylesheet that ships with JsPlumb has a rule for this class:
.jtk-surface-direct-render {
overflow:visible;
}
This rule takes into account that the content on the surface canvas is positioned and zoomed to fill up as much of the container as possible, right to the edge of the container. If you have elements with borders or outlines this rule will ensure the borders/outlines are not truncated when their element is right on the edge of the container.
If you do not include JsPlumb's default stylesheet you may wish to consider adding this rule to your own CSS.
Zoom Limits
In direct render mode, the surface does not restrict zoom to whatever levels zooming would otherwise be restricted to.
Navigating the canvas
The surface widget offers a number of methods for you to navigate your way around the rendered dataset.
Positioning
Several methods are available to assist you with positioning the surface canvas. These are discussed in greater detail in the API documentation:
centerOn
Takes a node/group as argument and positions the surface canvas such that the given node is at the center in both axes.centerOnHorizontally
Takes a node/group as argument and positions the surface canvas such that the given node is at the center in the horizontal axis.centerOnVertically
Takes a node/group as argument and positions the surface canvas such that the given node is at the center in the vertical axis.centerContent
Centers the tracked content inside the viewport, but does not adjust the current zoom (so the content may still extend past the viewport bounds)pan
Pans the canvas by a given amount in X and Y.setPan
Sets the position of the panned content's origin.positionElementAt
Positions a DOM element at a given X,Y on the canvas, in canvas coordinates (meaning it takes into account the current zoom and pan). This is not intended for use with elements the surface is managing: it is designed to be used with elements such as pop-ups that you may wish to position relative to the content in your canvas.positionElementAtEventLocation
Positions a DOM element at the apparent canvas location corresponding to the page location given by some event. This is not intended for use with elements the surface is managing: it is designed to be used with elements such as pop-ups that you may wish to position relative to the content in your canvas.positionElementAtPageLocation
Positions a DOM element at the apparent canvas location corresponding to the given page location. This is not intended for use with elements the surface is managing: it is designed to be used with elements such as pop-ups that you may wish to position relative to the content in your canvas.alignContent
Pan the canvas to align the content in one or both axes.alignContentLeft
Pan the canvas to align the content such that the left edge of the leftmost element is at the left of the viewport.alignContentRight
Pan the canvas to align the content such that the right edge of the rightmost element is at the right of the viewport.alignContentTop
Pan the canvas to align the content such that the top edge of the topmost element is at the top of the viewport.alignContentBottom
Pan the canvas to align the content such that the bottom edge of the bottom element is at the bottom of the viewport.Zooming
You can zoom the canvas in a number of different ways:
zoomToFit
Zooms the display so that all the tracked elements fit inside the viewport. This method will also, by default, increase the zoom if necessary - meaning the default behaviour is to adjust the zoom so that the content fills the viewport. You can suppress zoom increase by settingdoNotZoomIfVisible:true
on the
parameters to this method.
zoomToFitIfNecessary
Zooms the display so that all the tracked elements fit inside the viewport, but does not make any adjustments to zoom if all the elements are currently visible (it still does center the content though).zoomToElements
Zooms the viewport so that all of the given elements are visible.zoomToExtents
Zooms the display to fit the given extents. You can provide one or more sets of extents to this method, and their combined area will be calculated.zoomToBackground
Zooms the display so that the background (if one is set) fits inside the viewport.zoomToDecorator
Zooms the display to fit the canvas and content plus any elements added by the given decorator.Finding elements
Several methods are available to assist you to find elements in the canvas.
findIntersectingVertices
Finds vertices - Nodes or Groups - that intersect, or are enclosed by, a rectangle defined by the given origin and dimensions.findIntersectingNodes
Finds Nodes (not Groups) - that intersect a rectangle defined by the given origin and dimensions.findIntersectingGroups
Finds Groups (not Nodes) - that intersect a rectangle defined by the given origin and dimensions.Mapping coordinates
Every now and then you'll likely want to map between the surface's coordinate system and the page coordinate system. The surface offers a few methods to assist with this.
isInViewport
Returns whether or not the given point (relative to page origin) is within the viewport for the widget.fromPageLocation
Maps the given page location to a value relative to the viewport origin, allowing for zoom and pan of the canvas. This takes into account the offset of the viewport in the page so that what you get back is the mapped position relative to the target element's [left,top] corner. If you wish, you can supply true for 'doNotAdjustForOffset', to suppress that behavior.toPageLocation
Maps the given location relative to the viewport origin, to a page location, allowing for zoom and pan of the canvas. This takes into account the offset of the viewport in the page so that what you get back is the mapped position relative to the target element's [left,top] corner. If you wish, you can supply true for 'doNotAdjustForOffset', to suppress that behavior.Rendering options list
The full list of rendering options available is:
Name | Type | Description |
---|---|---|
addToDragSelectionOnSelect? | boolean | When true, vertices that are added to the underlying Toolkit's selection will be added to the current drag selection. Prior to 5.10.2 this flag's true state was the default behaviour, but the flag now defaults to false, and the Surface uses the concept of "drag groups" to manage dragging the set of selected elements together. For more information check out the Toolkit docs, specifically the section on element dragging. |
autoExitSelectMode? | boolean | Whether or not to automatically exit from 'select' mode after a lasso operation. A future version of the Toolkit will move this flag into the lasso plugin. |
clamp? | boolean | Whether or not to limit the canvas movement when dragging or zooming so that some part of the dataset is always visible. Defaults to true. |
clampToBackground? | boolean | When a background is in use, whether or not to clamp movement of the canvas so that some portion of the background is always visible. |
clampToBackgroundExtents? | boolean | When a background is in use, whether or not to clamp movement of the canvas so that the entire background is always visible. |
connectionDetachSelector? | If present, invoked when the user starts to detach a connection from some endpoint. This function allows
you to determine which connection to detach. Note that this is quite low level and requires you pass back a Connection object,
not an Edge. You can find the endpoint's connections via its connections member. | |
consumeRightClick? | boolean | Whether or not to consume right clicks, which ordinarily will cause a browser to show a context menu with some native browser functions. This defaults to true. |
debug? | boolean | Defaults to false. When true, the Surface will console log a few specific pieces of activity in the lifecycle of rendering a vertex. |
decorators? | Array<> | Optional list of decorators to attach to the Surface. |
defaults? | JsPlumbDefaults | Optional defaults to use for the underlying renderer. |
directRender? | boolean | Direct rendering is a mode in which the Surface disables pan/zoom, and adjusts its content so that the origin of the content is [0,0]. This mode can be used to embed the Surface into a read only UI (while still maintaining its dynamic connection to the underlying dataset) |
discardEdgeEditsOnDrag? | boolean | Defaults to false. When true, dragging either the source or target of some edge that has edits will cause those edits to be discarded. When false - the default value - JsPlumb attempts to retain as many of the edits as possible while still catering for the fact that the source or target has moved. |
dragOptions? | SurfaceDragOptions | Options for dragging vertices. |
edgeSnap? | SurfaceEdgeSnapOptions | Options for edge snap, which is off by default |
editablePaths? | boolean | If true, an EdgePathEditor will be registered on the Surface, with which you can interact via the startEditingPath(..) and stopEditingPath() methods on the Surface. |
elementsDraggable? | boolean | Whether or not the elements in the Surface should be draggable. Defaults to true. |
enableAnimation? | boolean | Whether or not to support animation of pan/zoom operations. |
enablePan? | boolean | Whether or not to enable panning of the canvas. Defaults to true. |
enhancedView? | boolean | Defaults to true, meaning node/group/edge definitions support parameters in their declarations, where the final values at render time are extracted from the data for the object being rendered. |
events? | Record | Optional map of handlers for various events generated by the Surface. |
fixedTransformOrigin? | PointXY | Optional fixed transform origin for the content. When this is supplied the zoom function does not change the transform origin, and neither does the pan. You can still zoom and pan but the zoom/pan is applied relative to the top/left corner of the content. |
grid? | SurfaceGridOptions | Options for imposing a grid onto the elements in the Surface. |
id? | string | Optional ID for the Surface. Allows you to retrieve this Surface from a toolkit instance's getRenderer(id) method. |
layout? | SurfaceLayoutSpec | Defines the layout to use. |
logicalPorts? | boolean | Defaults to false. When true, if a port is added to a vertex programmatically, the surface treats the vertex's DOM element as the DOM element for the port if it cannot find a specific element for the port. |
magnetize? | SurfaceMagnetizeOptions | Options for the magnetize functionality of the Surface. |
mode? | SurfaceMode | Mode to start in. Defaults to 'pan'. |
modelEvents? | Array<ModelEventSpec> | Optional map of event handlers. Each entry consists of the event name, a CSS selector to target,
and a callback function. Supplying this is equivalent to calling bindModelEvent(..) on a Surface. |
modelHeightAttribute? | string | Defines the name of the attribute in a given vertex's backing data that provides its height. Defaults to "height". If you have a UI with multiple renderers you can use this parameter to store multiple sets of sizes for a given vertex inside its data. |
modelLeftAttribute? | string | Defines the name of the attribute in a given vertex's backing data that provides its location in the X axis. Defaults to "left". If you have a UI with multiple renderers you can use this parameter to store multiple sets of locations for a given vertex inside its data. |
modelTopAttribute? | string | Defines the name of the attribute in a given vertex's backing data that provides its location in the Y axis. Defaults to "top". If you have a UI with multiple renderers you can use this parameter to store multiple sets of locations for a given vertex inside its data. |
modelWidthAttribute? | string | Defines the name of the attribute in a given vertex's backing data that provides its width. Defaults to "width". If you have a UI with multiple renderers you can use this parameter to store multiple sets of sizes for a given vertex inside its data. |
objectFilter? | Optional filter that can decide whether or not the Surface renders a specific node or group. By default all nodes and groups in the underlying dataset are rendered. | |
panFilter? | Optional function which is called at the start of panning and can return false to reject pan starting. | |
panWithMetaKey? | boolean | Optional, defaults to false. When true, the user must hold down the meta key (ctrl on windows) in order to pan. |
plugins? | Array<SurfacePluginSpec> | Optional list of plugins to attach to the Surface. |
propertyMappings? | PropertyMappings | Optional set of mappings from property values to edge definitions. |
refreshAutomatically? | boolean | Whether or not the automatically refresh the layout when model data changes. Defaults to true. |
refreshLayoutOnEdgeConnect? | boolean | When true, the Surface will run a refresh of the underlying layout whenever a new edge is established. This
defaults to false, but you might want to set this to true if you're using the Hierarchical or Hierarchy layouts,
because it has a bearing on the way they paint. However, if your users are able to drag vertices around, you may
not wish for the layout to move things that they have placed, which is why this defaults to false. |
relayoutOnGroupUpdate? | boolean | Defaults to false. When true, changes to a group cause the entire surface to perform a relayout. |
selection? | Optional Selection - or generator - to use as the dataset to render. If you supply this the Surface will render the contents of the selection, or the list of vertices that the given function returns. This is useful for such things as inspector windows for parts of your UI. | |
shapes? | SurfaceShapesOptions | Optional shape library that can render SVG shapes into node elements. When you provide a shape library to a surface, two things happen:
1. The surface registers a jtk-shape tag that your templates can use. The type of each node is used to extract an appropriate SVG shape definition from the shape library.
2. The 'exportToSvg()' method becomes available. Note that as of 6.5.1 SVG export is experimental, and has a few constraints/requirements - see the Toolkit docs for a discussion. |
simpleEdgeStyles? | boolean | From 6.2.0, defaults to true. Prior versions default this flag to false. Instructs the Surface to automatically extract
color , lineWidth , outlineWidth and outlineColor values from the backing data for edges, and to use these to
set the appearance of a connection for that edge. |
storePositionsInModel? | boolean | Whether or not to store vertex positions in the middle after running a layout. Defaults to false. A future release of the Toolkit will set this flag to true by default. |
templates? | Record | When using 'vanilla' Toolkit, you can provide a map of templates here rather than including them somewhere in the HTML of the page. |
useModelForSizes? | boolean | Defaults to false. When true, newly created nodes are sized according to values in their backing data, using the modelWidthAttribute and modelHeightAttribute as keys. |
useSvgContainer? | boolean | Defaults to false. When true, JsPlumb will use an SVG element as the container for all the other elements. You will need to ensure your templates/components write out SVG elements, and you will have to stick to SVG elements in any Decorators. |
view? | SurfaceViewOptions | Mappings of vertex/edge types to their rendering and behaviour. |
wheel? | SurfaceWheelOptions | Options for the behaviour of the mousewheel (which also covers two finger scrolling on a mac trackpad) |
zoom? | number | Starting zoom for the Surface. Defaults to 1. |
zoomRange? | ZoomRange | The zoom range for the Surface - minimum and maximum values, expressed as decimals. Defaults to [0.05, 3]. |
zoomToFit? | boolean | If true, zoom the display so that the dataset is entirely visible after initialisation. |
zoomToFitIfNecessary? | boolean | If true, zoom the display so that the dataset is entirely visible after initialisation, but only adjust the zoom level if the dataset is not already visible at the default zoom level. |