Skip to main content

HTML5 Canvas Drop Events

Konva does not support drop events. But you can write your own drop events detections. To detect drop target shape you have to move dragging object into another layer.

In this example you can see implementation of drop, dragenter, dragleave, dragover events.

Instructions: drag one shape over another. Or drag and drop one shape into another.

import Konva from 'konva';

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

const shapesLayer = new Konva.Layer();
const dragLayer = new Konva.Layer();

stage.add(shapesLayer);
stage.add(dragLayer);

const target = new Konva.Circle({
  x: 200,
  y: 100,
  radius: 50,
  fill: 'red',
  stroke: 'black',
  strokeWidth: 4,
});

const draggable = new Konva.Circle({
  x: 50,
  y: 100,
  radius: 30,
  fill: 'blue',
  draggable: true,
});

shapesLayer.add(target);
shapesLayer.add(draggable);

let dragShape = null;
let isDragging = false;
let isTargetHovered = false;

draggable.on('dragstart', (e) => {
  isDragging = true;
  dragShape = e.target;
  dragShape.moveTo(dragLayer);
  shapesLayer.draw();
  dragLayer.draw();
});

draggable.on('dragend', (e) => {
  isDragging = false;
  dragShape.moveTo(shapesLayer);
  dragShape = null;
  shapesLayer.draw();
  dragLayer.draw();

  if (isTargetHovered) {
    console.log('drop!');
  }
});

draggable.on('dragmove', () => {
  const pos = stage.getPointerPosition();
  const shape = shapesLayer.getIntersection(pos);

  if (shape === target) {
    if (!isTargetHovered) {
      isTargetHovered = true;
      target.fill('green');
      shapesLayer.draw();
      console.log('dragenter');
    }
    console.log('dragover');
  } else {
    if (isTargetHovered) {
      isTargetHovered = false;
      target.fill('red');
      shapesLayer.draw();
      console.log('dragleave');
    }
  }
});