Sooraj Chandran Sooraj Chandran - 4 months ago 38
Javascript Question

Get X and Y of a shape after dragging in Konva JS

I'm using Konva JS in my project. I'm adding a shape on a button click which is draggable. On click of the shape i need to get X and Y positions of the shape.

getX
and
getY
functions are returning the original X and Y. How can I update the X and Y after dragging.

Example 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>




Answer

If you need to get a mouse position you can use:

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