Modermo
Modermo

Reputation: 1992

Konva Drag element from outside canvas onto stage

I have a Konva stage that currently displays a series of shapes. I would like to have a shapes panel, where I can drag shapes and insert into the canvas.

There are currently two ways of doing this:

  1. Adding the Shapes Panel to the Konva stage as it's own layer and entity
  2. Having the Shapes Panel as a standalone HTML element outside the Konva stage and implement a draggable js library to handle dragging behaviour

I'd rather option 2; being able to style the shapes panel with CSS and yield a number of other DOM related benefits is more attractive to me right now.

I have the dragging behaviour sorted, but there is one issue: even though I've implemented stage mouseover events, dragging an element that originates from outside the canvas to on top of the canvas doesn't actually trigger the stage event listeners.

Is there a way around this?

What's interesting is that if you click and hold the mouse outside the element and hover over the canvas, the event listeners fire. But, when you're actually dragging an element (text, image), the event listeners do not fire...

Upvotes: 2

Views: 3733

Answers (1)

lavrton
lavrton

Reputation: 20373

Take a look into this demo: https://konvajs.org/docs/sandbox/Drop_DOM_Element.html

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 (with private method):
  stage.setPointersPositions(e);

  // now you can add a shape. We will add an image

  Konva.Image.fromURL('/assets/yoda.jpg', function(image) {
    layer.add(image);

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

    layer.draw();
  });
});

Upvotes: 5

Related Questions