javascriptdraggablekineticjsbounding

KinetikJS Keep bounds while dragging an object


Heyhey, while learning JS and using KineticJS I am stuck with a little problem.

As Iam not able to get my own code into a fiddle right now lets take this example: http://jsfiddle.net/m1erickson/n5xMs/

If we make the white rect also draggable:

        var white = new Kinetic.Rect({
        x: 20,
        y: 20,
        width: 300,
        height: 300,
        fill: 'white',
        stroke: 'black',
        strokeWidth: 2,
        draggable: true
    });

the dragBoundFunc won´t work correctly anymore if the white rect is moved around. While debugging this with coda2, I found that when the white rect is dragged around, that the x and y attrs do not change.

Why is that so? How do I manage to make the dragBoundFunc work for moving parent-shapes?

thanks in advance for your help.


Solution

  • First of all:

    I found that when the white rect is dragged around, that the x and y attrs do not change.

    No, they don't, because they're defined statically. If you wanted changing values, you'd want to get the updated values within the dragBoundFunc. It might be as simple as calculating them the same way they are now, but inside that function.

    How do I manage to make the dragBoundFunc work for moving parent-shapes?

    In your example the white rectangle isn't a parent of anything, it's just a shape drawn on the same stage as the orange rectangle. What you want to do is make the white shape background and the orange rectangle both children of the same node, and drag that. The most direct way to do this here would be to make the layer itself draggable, e.g.:

    var layer = new Kinetic.Layer({draggable: true});
    

    But how you do this is arbitrary. The white and orange boxes might also be children of another Kinetic.Container, for example.