Konva Drag and Drop

#atom

Interactive Object Manipulation System

Core Idea: Konva's drag and drop system provides intuitive object manipulation with built-in events, constraints, and multi-touch support, allowing developers to implement complex interaction behaviors with minimal code.

Key Elements

Implementation Examples

Basic Dragging

// Enable dragging on a shape
var circle = new Konva.Circle({
  x: 100,
  y: 100,
  radius: 50,
  fill: 'red',
  draggable: true
});

// Add event listeners for drag operations
circle.on('dragstart', function() {
  this.fill('green');
  layer.draw();
});

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

Constrained Dragging

// Create a shape with horizontal-only dragging
var rect = new Konva.Rect({
  x: 50,
  y: 100,
  width: 100,
  height: 50,
  fill: 'blue',
  draggable: true
});

// Constrain movement to horizontal axis
rect.on('dragmove', function() {
  // Keep the original y-position
  this.y(100);
});

// Create a shape with boundary constraints
var circle = new Konva.Circle({
  x: 100,
  y: 100,
  radius: 30,
  fill: 'yellow',
  draggable: true
});

// Constrain to a specific rectangular area
circle.on('dragmove', function() {
  var x = this.x();
  var y = this.y();
  
  // Define boundary box
  var minX = 30;
  var maxX = stage.width() - 30;
  var minY = 30;
  var maxY = stage.height() - 30;
  
  // Apply constraints
  if (x < minX) this.x(minX);
  if (x > maxX) this.x(maxX);
  if (y < minY) this.y(minY);
  if (y > maxY) this.y(maxY);
});

Connections

References

  1. Konva.js drag and drop documentation: https://konvajs.org/docs/drag_and_drop/Drag_and_Drop.html
  2. Complex drag and drop examples: https://konvajs.org/docs/drag_and_drop/Complex_Drag_and_Drop.html

#interaction #draganddrop #userinterface #canvas #touch


Connections:


Sources: