我在项目中使用Konva JS。我在可拖动的按钮单击上添加了形状。单击形状时,我需要获取形状的X和Y位置。 getXgetY函数返回原始的X和Y。拖动后如何更新X和Y。

下面的示例代码。

 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>

最佳答案

如果需要获取鼠标位置,可以使用:

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

关于javascript - 拖入Konva JS后获得形状的X和Y,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38409306/

10-09 17:36