Skip to main content

HTML5 Canvas Drag and Drop Events

To detect drag and drop events with Konva, we can use the on() method to bind dragstart, dragmove, or dragend events to a node. The on() method requires an event type and a function to be executed when the event occurs.

import Konva from 'konva';

const stage = new Konva.Stage({
  container: 'container',
  width: window.innerWidth,
  height: window.innerHeight,
});

const layer = new Konva.Layer();
stage.add(layer);

const text = new Konva.Text({
  x: 40,
  y: 40,
  text: 'Draggable Text',
  fontSize: 20,
  draggable: true,
  width: 200,
});
layer.add(text);

const status = new Konva.Text({
  x: 40,
  y: 100,
  text: '',
  fontSize: 16,
  width: 200,
});
layer.add(status);

text.on('dragstart', () => {
  status.text('drag started');
  layer.draw();
});

text.on('dragend', () => {
  status.text('drag ended');
  layer.draw();
});

text.on('dragmove', () => {
  status.text('dragging');
  layer.draw();
});