Skip to main content

HTML5 Canvas Drag and Drop an Image

To drag and drop an image 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.

import Konva from 'konva';

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

const layer = new Konva.Layer();

const imageObj = new Image();
imageObj.onload = () => {
  const yoda = new Konva.Image({
    x: 50,
    y: 50,
    image: imageObj,
    width: 106,
    height: 118,
    draggable: true,
  });

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

  layer.add(yoda);
  layer.draw();
};
imageObj.src = 'https://konvajs.org/assets/yoda.jpg';

stage.add(layer);