Get X and Y shapes after drag and drop in Konva JS

I am using Konva JS in my project. I am adding a form to a button that is being dragged. When I click on the shape, I need to get the X and Y position of the shape. Functions getXand getYreturn the original X and Y. How can I update X and Y after drag and drop.

Sample code below.

 var stage = new Konva.Stage({
        container: 'canvas', // id of container <div>
        width: 500,
        height:300
    });
    
 jQuery("#add-shape").click(function(){
 addShape();
 });
 
 var addShape = function(){
 
 console.log("add shape");
 
 var layer = new Konva.Layer();
 var parentContainer = new Konva.Rect({
            x: stage.getWidth() / 2,
            y: stage.getHeight() / 2,
            width: 200,
            height: 60,
            cornerRadius: 10,
            fill: '#ccc'
        });
        
        var smallCircle = new Konva.Circle({
            x: stage.getWidth() / 2 + 200,
            y: stage.getHeight() / 2 + 30,
            radius: 15,
            fill: "#F2784B",
            stroke: "white",
            strokeWidth: 2
        });
        
        smallCircle.on('click', function() {
         console.log(this.getX(),this.getY());
           addArrow(this.getX(),this.getY());
          //get current X and Y here instead of origina X and Y
        });
        layer.add(parentContainer);
        layer.add(smallCircle);
        layer.draggable('true');
        stage.add(layer);
}

var addArrow = function(arrowX,arrowY){
  var connectorLayer = new Konva.Layer();
	var connector = new Konva.Arrow({
            points: [arrowX,arrowY,arrowX+10,arrowY],
            pointerLength: 4,
            pointerWidth: 4,
            fill: 'black',
            stroke: 'black',
            strokeWidth: 2
        });
    connectorLayer.add(connector);
    stage.add(connectorLayer);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/konvajs/konva/1.0.2/konva.min.js"></script>
<button id="add-shape">
      Add shape
      </button>
<div id="canvas">
        
      </div>
Run code
+4
source share
1 answer

If you need to get the mouse position, you can use:

smallCircle.on('click', function() {
     console.log(stage.getPointerPosition());
});
+5
source

Source: https://habr.com/ru/post/1648083/


All Articles