Question

I want to implement a function which takes as parameters a group and a rectangle and checks if the rectangle belongs in the group. In case it belongs in the group, I want to completely remove that rectangle from the group and from the layer. I tried group.remove() and group.getChildren()[i].remove but I think that they do not completely remove the rectangle. After some effort, I managed to do what follows which seems silly to me:

/**
 * Checks if a rectangle belongs in any of the existing groups
 */
function removesFromGroup(group, tempRect) {

    /**
     * I created a bin group and I send the rectangle to this group by using group.moveTo(bin)
     */
    var bin = new Kinetic.Group({
        name: 'bin',
        x: -480,
        y: -50
    });

    for (var j = 0; j < group.getChildren().length; j++) {
        //  var groupCube_x = (groups[i].getChildren()[j]).getAbsolutePosition().x;

        if (group.getChildren()[j] == tempRect) {
            tempRect.moveTo(bin);

            // alert("Move to bin");
            //tempRect.remove();
            //tempRect.getParent().remove(bin);

            //bin.destroy(); 


            layer.draw();
        }
    }
    return false;
}

However, even though this works for a case, I am still facing problems with the fact that I don't how to completely remove (delete) a rectangle or a group from the layer or stage.

I can provide more information of what exactly I am trying to do, in case this is not clear.

Était-ce utile?

La solution 2

Javascript also provides a nice method (.indexOf()) for checking if an element is part of an array, so you can skip the loops altogether. Then after you've confirmed the node is part of the group, you can use the .destroy() method to, well, destroy it.

function removesFromGroup(group, tempRect) {
    if (group.getChildren().indexOf(tempRect) !== -1)
        tempRect.destroy();
        layer.draw();
    });

    return false;
}

Autres conseils

Every Kinetic Node (Shapes, Layers, Groups, etc) has a method called destroy(), which removes and destroys itself, see also here: http://kineticjs.com/docs/Kinetic.Node.html.

So you in your case you could call tempRect.destroy() and the rectangle will be removed from everywhere and destroy itself. Of course you need to do a draw() on one of its parents, but you are already doing that. You can also remove your bin Group then, this should not be needed anymore :-).

/**
 * Checks if a rectangle belongs in any of the existing groups and 
 * destroys it if so.
 */
function removesFromGroup(group, tempRect) {

    group.getChildren().forEach(function(child){

        if (child == tempRect) {
            tempRect.destroy();
            layer.draw();
        }        
    });

    return false;
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top