How to drag and drop DOM image into the canvas

获取Konva最新的信息

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

The first image you see is a DOM image. We can use HTML5 drag&drop to enable its dragging.

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.

Konva Elastic Stars Demoview raw
<!DOCTYPE html>
<html>
<head>
<script src="https://unpkg.com/[email protected]/konva.min.js"></script>
<meta charset="utf-8" />
<title>Konva Drop DOM element Demo</title>
<style>
body {
margin: 0;
padding: 0;
overflow: hidden;
background-color: #f0f0f0;
}

#container {
background-color: rgba(0, 0, 0, 0.1);
}

p {
margin: 4px;
}

#drag-items img {
height: 100px;
}
</style>
</head>

<body>
<p>
Drag&drop yoda into the grey area.
</p>
<div id="drag-items">
<img src="/assets/yoda.jpg" draggable="true" />
<img src="/assets/darth-vader.jpg" draggable="true" />
</div>
<div id="container"></div>
<script>
var width = window.innerWidth;
var height = window.innerHeight;

var stage = new Konva.Stage({
container: 'container',
width: width,
height: height
});
var layer = new Konva.Layer();
stage.add(layer);

// what is url of dragging element?
var itemURL = '';
document
.getElementById('drag-items')
.addEventListener('dragstart', function(e) {
itemURL = e.target.src;
});

var con = stage.container();
con.addEventListener('dragover', function(e) {
e.preventDefault(); // !important
});

con.addEventListener('drop', function(e) {
e.preventDefault();
// now we need to find pointer position
// we can't use stage.getPointerPosition() here, because that event
// is not registered by Konva.Stage
// we can register it manually:
stage.setPointersPositions(e);

Konva.Image.fromURL(itemURL, function(image) {
layer.add(image);

image.position(stage.getPointerPosition());
image.draggable(true);

layer.draw();
});
});
</script>
</body>
</html>
Next