Konva Event Handling

#atom

Interactive Canvas Element Management

Core Idea: Konva provides a robust event system that brings DOM-like event handling to Canvas elements, enabling desktop and mobile interactions through a unified API that efficiently detects target shapes using hit detection.

Key Elements

Implementation Example

// Create an interactive shape with events
var circle = new Konva.Circle({
  x: 100,
  y: 100,
  radius: 50,
  fill: 'red',
  stroke: 'black',
  strokeWidth: 4
});

// Mouse events
circle.on('mouseover', function() {
  this.fill('yellow');
  layer.draw();
});

circle.on('mouseout', function() {
  this.fill('red');
  layer.draw();
});

// Touch events
circle.on('touchstart', function() {
  this.stroke('green');
  layer.draw();
});

// Attribute change events
circle.on('radiusChange', function() {
  console.log('Circle radius changed to: ' + this.radius());
});

// Drag and drop setup
circle.draggable(true);
circle.on('dragstart', function() {
  this.opacity(0.5);
  layer.draw();
});

circle.on('dragend', function() {
  this.opacity(1);
  layer.draw();
  console.log('Final position: x=' + this.x() + ', y=' + this.y());
});

Connections

References

  1. Konva.js events documentation: https://konvajs.org/docs/events/Binding_Events.html
  2. Drag and drop documentation: https://konvajs.org/docs/drag_and_drop/Drag_and_Drop.html

#events #interactivity #canvas #userinterface #eventhandling


Connections:


Sources: