Konva Node Hierarchy

#atom

Organizational Structure for Canvas Elements

Core Idea: Konva's node hierarchy provides an object-oriented structure for organizing canvas elements with inheritance and nesting capabilities, enabling both logical grouping and efficient manipulation of complex scenes.

Key Elements

Implementation Examples

Creating a Hierarchical Structure

// Create the base stage
var stage = new Konva.Stage({
  container: 'container',
  width: 500,
  height: 500
});

// Create a layer
var layer = new Konva.Layer();
stage.add(layer);

// Create a group for organization
var group = new Konva.Group({
  x: 100,
  y: 100
});
layer.add(group);

// Add shapes to the group
var circle = new Konva.Circle({
  x: 0,         // Relative to group (100 + 0 = 100 in stage coordinates)
  y: 0,         // Relative to group (100 + 0 = 100 in stage coordinates)
  radius: 50,
  fill: 'red'
});
group.add(circle);

var rect = new Konva.Rect({
  x: 70,        // Relative to group (100 + 70 = 170 in stage coordinates)
  y: 0,         // Relative to group (100 + 0 = 100 in stage coordinates)
  width: 50,
  height: 50,
  fill: 'blue'
});
group.add(rect);

// Draw the layer
layer.draw();

Finding and Manipulating Nodes

// Find all circles in the stage
var circles = stage.find('Circle');
circles.forEach(function(circle) {
  circle.fill('green');
});

// Find a specific node by ID
var specificShape = stage.findOne('#myUniqueId');
if (specificShape) {
  specificShape.scale({ x: 1.5, y: 1.5 });
}

// Find all nodes with a name (like a CSS class)
var blueShapes = stage.find('.blueShape');
blueShapes.forEach(function(shape) {
  shape.opacity(0.5);
});

// Apply transformation to a group (affects all children)
group.rotate(45);
layer.draw();

Connections

References

  1. Konva.js node documentation: https://konvajs.org/api/Konva.Node.html
  2. Konva selectors documentation: https://konvajs.org/docs/selectors/Selectors.html

#hierarchicalstructure #scenegraph #canvas #graphicsorganization #objectoriented


Connections:


Sources: