Node
new Konva.Node(config)
Node constructor. Nodes are entities that can be transformed, layered, and have bound events. The stage, layers, groups, and shapes all extend Node.
Parameters
| Name | Type | Description |
|---|---|---|
| config | Object | |
| x (optional) | Number | |
| y (optional) | Number | |
| width (optional) | Number | |
| height (optional) | Number | |
| visible (optional) | Boolean | |
| listening (optional) | Boolean | whether or not the node is listening for events |
| id (optional) | String | unique id |
| name (optional) | String | non-unique name |
| opacity (optional) | Number | determines node opacity. Can be any number between 0 and 1 |
| scale (optional) | Object | set scale |
| scaleX (optional) | Number | set scale x |
| scaleY (optional) | Number | set scale y |
| rotation (optional) | Number | rotation in degrees |
| offset (optional) | Object | offset from center point and rotation point |
| offsetX (optional) | Number | set offset x |
| offsetY (optional) | Number | set offset y |
| draggable (optional) | Boolean | makes the node draggable. When stages are draggable, you can drag and drop the entire stage by dragging any portion of the stage |
| dragDistance (optional) | Number | |
| dragBoundFunc (optional) | function |
Own Methods
clearCache()
clear cached canvas
Returns: Konva.Node
Example:
node.clearCache();
cache(config)
cache node to improve drawing performance, apply filters, or create more accurate hit regions. For all basic shapes size of cache canvas will be automatically detected. If you need to cache your custom Konva.Shape instance you have to pass shape's bounding box properties. Look at https://konvajs.org/docs/performance/Shape_Caching.html for more information.
Parameters:
config(Object) (optional)config.x(Number) (optional)config.y(Number) (optional)config.width(Number) (optional)config.height(Number) (optional)config.offset(Number) (optional): increase canvas size byoffsetpixel in all directions.config.drawBorder(Boolean) (optional): when set to true, a red border will be drawn around the cached region for debugging purposesconfig.pixelRatio(Number) (optional): change quality (or pixel ratio) of cached image. pixelRatio = 2 will produce 2x sized cache.config.imageSmoothingEnabled(Boolean) (optional): control imageSmoothingEnabled property of created canvas for cacheconfig.hitCanvasPixelRatio(Number) (optional): change quality (or pixel ratio) of cached hit canvas.
Returns: Konva.Node
Example:
// cache a shape with the x,y position of the bounding box at the center and
// the width and height of the bounding box equal to the width and height of
// the shape obtained from shape.width() and shape.height()
image.cache();
// cache a node and define the bounding box position and size
node.cache({
x: -30,
y: -30,
width: 100,
height: 200
});
// cache a node and draw a red border around the bounding box
// for debugging purposes
node.cache({
x: -30,
y: -30,
width: 100,
height: 200,
offset : 10,
drawBorder: true
});
isCached()
determine if node is currently cached
Returns: Boolean
getClientRect(config)
Return client rectangle {x, y, width, height} of node. This rectangle also include all styling (strokes, shadows, etc). The purpose of the method is similar to getBoundingClientRect API of the DOM.
Parameters:
config(Object)config.skipTransform(Boolean) (optional): should we apply transform to node for calculating rect?config.skipShadow(Boolean) (optional): should we apply shadow to the node for calculating bound box?config.skipStroke(Boolean) (optional): should we apply stroke to the node for calculating bound box?config.relativeTo(Object) (optional): calculate client rect relative to one of the parents
Returns: Object rect with {x, y, width, height} properties
Example:
var rect = new Konva.Rect({
width : 100,
height : 100,
x : 50,
y : 50,
strokeWidth : 4,
stroke : 'black',
offsetX : 50,
scaleY : 2
});
// get client rect without think off transformations (position, rotation, scale, offset, etc)
rect.getClientRect({ skipTransform: true});
// returns {
// x : -2, // two pixels for stroke / 2
// y : -2,
// width : 104, // increased by 4 for stroke
// height : 104
//}
// get client rect with transformation applied
rect.getClientRect();
// returns Object {x: -2, y: 46, width: 104, height: 208}
on(evtStr, handler)
bind events to the node. KonvaJS supports mouseover, mousemove, mouseout, mouseenter, mouseleave, mousedown, mouseup, wheel, contextmenu, click, dblclick, touchstart, touchmove, touchend, tap, dbltap, dragstart, dragmove, and dragend events. Pass in a string of events delimited by a space to bind multiple events at once such as 'mousedown mouseup mousemove'. Include a namespace to bind an event by name such as 'click.foobar'.
Parameters:
evtStr(String): e.g. 'click', 'mousedown touchstart', 'mousedown.foo touchstart.foo'handler(function): The handler function. The first argument of that function is event object. Event object hastargetas main target of the event,currentTargetas current node listener andevtas native browser event.
Returns: Konva.Node
Example:
// add click listener
node.on('click', function() {
console.log('you clicked me!');
});
// get the target node
node.on('click', function(evt) {
console.log(evt.target);
});
// stop event propagation
node.on('click', function(evt) {
evt.cancelBubble = true;
});
// bind multiple listeners
node.on('click touchstart', function() {
console.log('you clicked/touched me!');
});
// namespace listener
node.on('click.foo', function() {
console.log('you clicked/touched me!');
});
// get the event type
node.on('click tap', function(evt) {
var eventType = evt.type;
});
// get native event object
node.on('click tap', function(evt) {
var nativeEvent = evt.evt;
});
// for change events, get the old and new val
node.on('xChange', function(evt) {
var oldVal = evt.oldVal;
var newVal = evt.newVal;
});
// get event targets
// with event delegations
layer.on('click', 'Group', function(evt) {
var shape = evt.target;
var group = evt.currentTarget;
});
off(evtStr)
remove event bindings from the node. Pass in a string of event types delimmited by a space to remove multiple event bindings at once such as 'mousedown mouseup mousemove'. include a namespace to remove an event binding by name such as 'click.foobar'. If you only give a name like '.foobar', all events in that namespace will be removed.
Parameters:
evtStr(String): e.g. 'click', 'mousedown touchstart', '.foobar'
Returns: Konva.Node
Example:
// remove listener
node.off('click');
// remove multiple listeners
node.off('click touchstart');
// remove listener by name
node.off('click.foo');
remove()
remove a node from parent, but don't destroy. You can reuse the node later.
Returns: Konva.Node
Example:
node.remove();
destroy()
remove and destroy a node. Kill it and delete forever! You should not reuse node after destroy(). If the node is a container (Group, Stage or Layer) it will destroy all children too.
Example:
node.destroy();
getAttr(attr)
get attr
Parameters:
attr(String)
Returns: Integer|String|Object|Array
Example:
var x = node.getAttr('x');
getAncestors()
get ancestors
Returns: Array
Example:
shape.getAncestors().forEach(function(node) {
console.log(node.id());
})
getAttrs()
get attrs object literal
Returns: Object
setAttrs(config)
set multiple attrs at once using an object literal
Parameters:
config(Object): object containing key value pairs
Returns: Konva.Node
Example:
node.setAttrs({
x: 5,
fill: 'red'
});
isListening()
determine if node is listening for events by taking into account ancestors. Parent | Self | isListening listening | listening | ----------+-----------+------------ T | T | T T | F | F F | T | F F | F | F
Returns: Boolean
isVisible()
determine if node is visible by taking into account ancestors. Parent | Self | isVisible visible | visible | ----------+-----------+------------ T | T | T T | F | F F | T | F F | F | F
Returns: Boolean
show()
show node. set visible = true
Returns: Konva.Node
hide()
hide node. Hidden nodes are no longer detectable
Returns: Konva.Node
getAbsoluteZIndex()
get absolute z-index which takes into account sibling and ancestor indices
Returns: Integer
getDepth()
get node depth in node tree. Returns an integer. e.g. Stage depth will always be 0. Layers will always be 1. Groups and Shapes will always be >= 2
Returns: Integer
getRelativePointerPosition()
get position of first pointer (like mouse or first touch) relative to local coordinates of current node
Returns: Konva.Node
Example:
// let's think we have a rectangle at position x = 10, y = 10
// now we clicked at x = 15, y = 15 of the stage
// if you want to know position of the click, related to the rectangle you can use
rect.getRelativePointerPosition();
getAbsolutePosition(Ancestor)
get absolute position of a node. That function can be used to calculate absolute position, but relative to any ancestor
Parameters:
Ancestor(Object): optional ancestor node
Returns: Konva.Node
Example:
// returns absolute position relative to top-left corner of canvas
node.getAbsolutePosition();
// calculate absolute position of node, inside stage
// so stage transforms are ignored
node.getAbsolutePosition(stage)
move(change)
move node by an amount relative to its current position
Parameters:
change(Object)change.x(Number)change.y(Number)
Returns: Konva.Node
Example:
// move node in x direction by 1px and y direction by 2px
node.move({
x: 1,
y: 2
});
rotate(theta)
rotate node by an amount in degrees relative to its current rotation
Parameters:
theta(Number)
Returns: Konva.Node
moveToTop()
move node to the top of its siblings
Returns: Boolean
moveUp()
move node up
Returns: Boolean flag is moved or not
moveDown()
move node down
Returns: Boolean
moveToBottom()
move node to the bottom of its siblings
Returns: Boolean
getAbsoluteOpacity()
get absolute opacity
Returns: Number
moveTo(newContainer)
move node to another container
Parameters:
newContainer(Container)
Returns: Konva.Node
Example:
// move node from current layer into layer2
node.moveTo(layer2);
toObject()
convert Node into an object for serialization. Returns an object.
Returns: Object
toJSON()
convert Node into a JSON string. Returns a JSON string.
Returns: String
getParent()
get parent container
Returns: Konva.Node
findAncestors(selector, includeSelf, stopNode)
get all ancestors (parent then parent of the parent, etc) of the node
Parameters:
selector(String): selector for searchincludeSelf(Boolean) (optional): show we think that node is ancestro itself?stopNode(Konva.Node) (optional): optional node where we need to stop searching (one of ancestors)
Returns: Array [ancestors]
Example:
// get one of the parent group
var parentGroups = node.findAncestors('Group');
findAncestor(selector, includeSelf, stopNode)
get ancestor (parent or parent of the parent, etc) of the node that match passed selector
Parameters:
selector(String): selector for searchincludeSelf(Boolean) (optional): show we think that node is ancestro itself?stopNode(Konva.Node) (optional): optional node where we need to stop searching (one of ancestors)
Returns: Konva.Node ancestor
Example:
// get one of the parent group
var group = node.findAncestors('.mygroup');
getLayer()
get layer ancestor
Returns: Konva.Layer
getStage()
get stage ancestor
Returns: Konva.Stage
fire(eventType, evt, bubble)
fire event
Parameters:
eventType(String): event type. can be a regular event, like click, mouseover, or mouseout, or it can be a custom event, like myCustomEventevt(Event) (optional): event objectbubble(Boolean) (optional): setting the value to false, or leaving it undefined, will result in the event not bubbling. Setting the value to true will result in the event bubbling.
Returns: Konva.Node
Example:
// manually fire click event
node.fire('click');
// fire custom event
node.fire('foo');
// fire custom event with custom event object
node.fire('foo', {
bar: 10
});
// fire click event that bubbles
node.fire('click', null, true);
getAbsoluteTransform()
get absolute transform of the node which takes into account its ancestor transforms
Returns: Konva.Transform
getAbsoluteScale()
get absolute scale of the node which takes into account its ancestor scales
Returns: Object
Example:
// get absolute scale x
var scaleX = node.getAbsoluteScale().x;
getAbsoluteRotation()
get absolute rotation of the node which takes into account its ancestor rotations
Returns: Number
Example:
// get absolute rotation
var rotation = node.getAbsoluteRotation();