Search code examples
kineticjs

Kinetic JS - Is there a way to return x,y coordinates while dragging?


I am making a toggle slider that moves up and down with Kinetic JS. Here is my draggable toggle:

this.toggle = new Kinetic.Rect({
        x: (this.stage.getWidth() / 2) - 20,
        y: 210,
        shadowColor: '#95BA91',
        shadowOffsetX: 5,
        shadowOffsetY: 5,
        width: 40,
        height: 15,
        fill: '#FFF',
        cornerRadius: 3,
        draggable: true,
        dragBoundFunc: function( pos ) {
            return {
                x: this.getAbsolutePosition().x,
                y: pos.y
            }
        }
    });

I am trying to return the y coordinate of the toggle so I can increment a counter based on the toggle's height. Every method I have tried returns the original value of y during and after the drag. Is there a way to get the changed y value? Here are the methods I already have tried:

getY(), getAbsolutePosition().y, dragDistance(), .y(), getOffset().y, getPosition().y


Solution

  • I think you misunderstood the use of dragBoundFunc.

    dragBoundFunc is mainly used to restrict in some way the movement of the shape when it is being dragged.

    What you should do is attach a dragmove event listener to your toggle shape, which will fire when you're dragging the shape.

    Take a look at this jsfiddle

    The Y coordinate is being printed in the browser's console everytime the toggle shape is being dragged.