Skip to main content

HTML5 Canvas Drag and Drop Tutorial

To drag and drop shapes with Konva, we can set the draggable property to true when we instantiate a shape, or we can use the draggable() method. The draggable() method enables drag and drop for both desktop and mobile applications automatically.

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 circle = new Konva.Circle({
  x: stage.width() / 2,
  y: stage.height() / 2,
  radius: 70,
  fill: 'red',
  stroke: 'black',
  strokeWidth: 4,
  draggable: true,
});

// add cursor styling
circle.on('mouseover', function () {
  document.body.style.cursor = 'pointer';
});
circle.on('mouseout', function () {
  document.body.style.cursor = 'default';
});

layer.add(circle);