Skip to main content

HTML5 Canvas Drag and Drop a Group Tutorial

To drag and drop groups with Konva, we can set the draggable property of the config object to true when the group is instantiated, or we can use the draggable() method.

Note: remember, dragging a group, do not change the x and y properties of any of the children nodes. Instead properties of group itself are changed.

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 group = new Konva.Group({
  draggable: true,
});
layer.add(group);

const colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple'];

for (let i = 0; i < 6; i++) {
  const box = new Konva.Rect({
    x: i * 30 + 10,
    y: i * 18 + 40,
    width: 100,
    height: 50,
    name: colors[i],
    fill: colors[i],
    stroke: 'black',
    strokeWidth: 4,
  });
  group.add(box);
}

group.on('mouseover', function () {
  document.body.style.cursor = 'move';
});
group.on('mouseout', function () {
  document.body.style.cursor = 'default';
});