最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get X and Y of a shape after dragging in Konva JS - Stack Overflow

programmeradmin3浏览0评论

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=".1.1/jquery.min.js"></script>
<script src=".0.2/konva.min.js"></script>
<button id="add-shape">
      Add shape
      </button>
<div id="canvas">
        
      </div>

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>

Share Improve this question asked Jul 16, 2016 at 8:28 SoorajSooraj 10.6k12 gold badges67 silver badges103 bronze badges
Add a comment  | 

5 Answers 5

Reset to default 7

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

smallCircle.on('click', function() {
     console.log(stage.getPointerPosition());
});
    box.on('mouseout', function () {
        document.body.style.cursor = 'default';
        console.log(box.attrs.x);
        console.log(box.attrs.y);
    });

I don't know if this is what you're looking for and it's too late but i'll post it anyway for future developers.. Lets say this is my watermark image inside the layer and bluh bluh and i want it's position getX() and getY(): I use the group like this:

First the regular stuff to add the image:

        function update(activeAnchor) {
        var group = activeAnchor.getParent();

        var topLeft = group.get('.topLeft')[0];
        var topRight = group.get('.topRight')[0];
        var bottomRight = group.get('.bottomRight')[0];
        var bottomLeft = group.get('.bottomLeft')[0];
        var image = group.get('Image')[0];

        var anchorX = activeAnchor.getX();
        var anchorY = activeAnchor.getY();

        // update anchor positions
        switch (activeAnchor.getName()) {
            case 'topLeft':
                topRight.setY(anchorY);
                bottomLeft.setX(anchorX);
                break;
            case 'topRight':
                topLeft.setY(anchorY);
                bottomRight.setX(anchorX);
                break;
            case 'bottomRight':
                bottomLeft.setY(anchorY);
                topRight.setX(anchorX);
                break;
            case 'bottomLeft':
                bottomRight.setY(anchorY);
                topLeft.setX(anchorX);
                break;
        }

        image.position(topLeft.position());

        var width = topRight.getX() - topLeft.getX();
        var height = bottomLeft.getY() - topLeft.getY();
        if (width && height) {
            image.width(width);
            image.height(height);
        }
    }
    function addAnchor(group, x, y, name) {
        var stage = group.getStage();
        var layer = group.getLayer();

        var anchor = new Konva.Circle({
            x: x,
            y: y,
            stroke: '#666',
            fill: '#ddd',
            strokeWidth: 2,
            radius: 8,
            name: name,
            draggable: true,
            dragOnTop: false
        });

        anchor.on('dragmove', function () {
            update(this);
            layer.draw();
        });
        anchor.on('mousedown touchstart', function () {
            group.setDraggable(false);
            this.moveToTop();
        });
        anchor.on('dragend', function () {
            group.setDraggable(true);
            layer.draw();
        });
        // add hover styling
        anchor.on('mouseover', function () {
            var layer = this.getLayer();
            document.body.style.cursor = 'pointer';
            this.setStrokeWidth(4);
            layer.draw();
        });
        anchor.on('mouseout', function () {
            var layer = this.getLayer();
            document.body.style.cursor = 'default';
            this.setStrokeWidth(2);
            layer.draw();
        });

        group.add(anchor);
    }

    var stage = new Konva.Stage({
        container: 'container',
        width: 595,
        height: 842
    });

    var layer = new Konva.Layer();
    stage.add(layer);
    //WaterMark
    var WaterMarkImg = new Konva.Image({
        width: 595,
        height: 842
    });
    var WaterMarkGroup = new Konva.Group({
        x: 0,
        y: 0,
        draggable: true
    });
    layer.add(WaterMarkGroup);
    WaterMarkGroup.add(WaterMarkImg);
    addAnchor(WaterMarkGroup, 0, 0, 'topLeft');
    addAnchor(WaterMarkGroup, 595, 0, 'topRight');
    addAnchor(WaterMarkGroup, 595, 842, 'bottomRight');
    addAnchor(WaterMarkGroup, 0, 842, 'bottomLeft');

    var imageObj1 = new Image();
    imageObj1.onload = function () {
        WaterMarkImg.image(imageObj1);
        layer.draw();
    };
    imageObj1.src = "some image Url";

and this is simply the getX(): very simple

    var x = WaterMarkGroup.getX();
        alert(x);

I hope this helps anyone looking for it.

This is not the exact answer for the question. point is the draggable shape.

point.on('dragmove', (t) => {
    console.log("dragmove", t.target.x(), t.target.y());
});

use shape.getAttr("x") and shape.getAttr("y"), following is my code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <!--mobile friendly-->
    <meta name="viewport" content="width=device-width, user-scalable=yes">
</head>
<body>
<div id="c"></div>
<script type="module">
    import "../../node_modules/konva/konva.js"

    var stage = new Konva.Stage({
        container: "#c",
        width: 500,
        height: 500
    })
    var layer = new Konva.Layer()
    stage.add(layer)
    var c = (x, y) => {
        return new Konva.Circle({
            x: x,
            y: y,
            stroke: "lightblue",
            strokeWidth: 2,
            radius: 10,
            draggable: true
        })
    }
    let c1 = c(50, 50)
    layer.add(c1)
    var c2 = c(100, 50)
    layer.add(c2)
    c1.on("dragmove", () => {
        c2.setAttr("y", c1.getAttr("y"))
    })
    layer.draw()
</script>
</body>
</html>
发布评论

评论列表(0)

  1. 暂无评论