Skip to main content

How to drag and drop DOM image into the canvas

In this demo we will demonstrate how drop DOM element that is placed outside of canvas into the stage.

The first image is a DOM image. We can use HTML drag and drop to make it draggable.

You will need some extra step if you need to enable drag&drop for DOM element on touch devices. You can read here for more info.

Instructions: drag&drop yoda into the canvas.

import Konva from 'konva';

const width = window.innerWidth;
const height = window.innerHeight;

// Add DOM elements to render outside the container
document.getElementById('container').insertAdjacentHTML(
'beforebegin',
`
<p>Drag&drop yoda into the grey area.</p>
<div id="drag-items">
<img src="https://konvajs.org/assets/yoda.jpg" draggable="true" style="height: 100px; margin: 5px;" />
<img src="https://konvajs.org/assets/darth-vader.jpg" draggable="true" style="height: 100px; margin: 5px;" />
</div>
`
);

// Style the container with grey background
document.getElementById('container').style.backgroundColor = 'rgba(0, 0, 0, 0.1)';

// Create stage and layer
const stage = new Konva.Stage({
container: 'container',
width: width,
height: height - 150, // leave space for the DOM elements
});

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

// Track URL of the dragging element
let itemURL = '';
document
.getElementById('drag-items')
.addEventListener('dragstart', function (e) {
itemURL = e.target.src;
});

// Handle dragover on container
const container = stage.container();
container.addEventListener('dragover', function (e) {
e.preventDefault(); // important - must prevent default behavior
});

// Handle drop on container
container.addEventListener('drop', function (e) {
e.preventDefault();

// Register the pointer position manually since this is a DOM event
stage.setPointersPositions(e);

// Load the image and add it to the layer
Konva.Image.fromURL(itemURL, function (image) {
// Calculate appropriate size based on image dimensions
const img = image.image();
const maxDimension = 100;
let width = img.width;
let height = img.height;

if (width > height) {
height = (height / width) * maxDimension;
width = maxDimension;
} else {
width = (width / height) * maxDimension;
height = maxDimension;
}

image.size({
width: width,
height: height
});

layer.add(image);
image.position(stage.getPointerPosition());
image.draggable(true);
});
});