Konva Event Handling
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
-
Event Types:
- User input events: click, dblclick, mouseover, mouseout, mousemove, touchstart, touchend, tap, dbltap
- Attribute change events: xChange, yChange, scaleXChange, fillChange, etc.
- Drag and drop events: dragstart, dragmove, dragend
- Custom events: Can emit and listen for custom event types
-
Hit Detection:
- Uses a secondary "hit graph" canvas for efficient shape detection
- Creates invisible rendering of shapes for pixel-perfect hit testing
- Automatically handles complex shapes and transparency regions
-
Event Binding:
- Node.on(eventName, callback): Attach event listeners
- Node.off(eventName): Remove event listeners
- Event bubbling support through node hierarchy
-
Event Object:
- Contains event type and coordinates
- Provides target node reference
- Supports stopping propagation and preventing default behavior
-
Mobile Support:
- Touch events are normalized across platforms
- Multi-touch gesture recognition
- Mobile and desktop event mapping (e.g., tap ≈ click)
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
- Related Concepts: Konva.js, Konva Stage Architecture, Hit Detection, Event Propagation
- Broader Context: DOM Events, User Interaction Patterns, Event-Driven Programming
- Applications: Interactive Data Visualization, Canvas-based UI Components, Drawing Applications
References
- Konva.js events documentation: https://konvajs.org/docs/events/Binding_Events.html
- Drag and drop documentation: https://konvajs.org/docs/drag_and_drop/Drag_and_Drop.html
#events #interactivity #canvas #userinterface #eventhandling
Connections:
Sources: