Custom Shapes in Konva

#atom

Creating Specialized Graphical Elements

Core Idea: Konva enables the creation of custom shapes through the Konva.Shape class, providing direct access to the canvas context while maintaining integration with the framework's event system, styling capabilities, and node hierarchy.

Key Elements

Implementation Examples

Basic Custom Shape

// Create a custom triangle shape
var triangle = new Konva.Shape({
  x: 100,
  y: 100,
  sceneFunc: function(context) {
    // Begin a new path
    context.beginPath();
    
    // Draw triangle
    context.moveTo(0, 0);
    context.lineTo(50, 0);
    context.lineTo(25, 50);
    context.closePath();
    
    // Apply Konva fill and stroke styles
    context.fillStrokeShape(this);
  },
  // Apply Konva styling
  fill: 'red',
  stroke: 'black',
  strokeWidth: 2
});

// Add to layer and draw
layer.add(triangle);
layer.draw();

Complex Custom Shape with Custom Hit Detection

// Create a complex custom shape with different hit region
var customShape = new Konva.Shape({
  x: 200,
  y: 100,
  draggable: true,
  
  // Visual appearance
  sceneFunc: function(context) {
    context.beginPath();
    
    // Draw a complex shape
    context.moveTo(0, 0);
    context.quadraticCurveTo(25, -50, 50, 0);
    context.quadraticCurveTo(75, 50, 100, 0);
    context.quadraticCurveTo(75, 25, 50, 50);
    context.quadraticCurveTo(25, 75, 0, 50);
    context.closePath();
    
    // Apply Konva fill and stroke
    context.fillStrokeShape(this);
  },
  
  // Custom hit region (simplified for better performance)
  hitFunc: function(context) {
    context.beginPath();
    
    // Use a simpler shape for hit detection
    context.rect(0, 0, 100, 50);
    
    // Must call this for hit detection to work
    context.fillStrokeShape(this);
  },
  
  fill: 'yellow',
  stroke: 'blue',
  strokeWidth: 2
});

layer.add(customShape);
layer.draw();

Connections

References

  1. Konva.js custom shape documentation: https://konvajs.org/docs/shapes/Custom.html
  2. Canvas 2D context documentation: https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D

#customshapes #canvas #vectorgraphics #drawing #graphicsprogramming


Connections:


Sources: