Kinetic JS - how do you hide all the anchors for a given group ID

前端 未结 1 2012
死守一世寂寞
死守一世寂寞 2021-01-26 02:05

Please take a look at the following Link

I have the following code:

// hide all anchors
            var children = group.getChildren();
            for(v         


        
相关标签:
1条回答
  • 2021-01-26 02:49

    This is why I wish KineticJS supported multiple names. This method would be much cleaner if we were able to use something like:

    get('.anchor')

    But since we need to name the anchors because there will be multiple instances of each anchor, we cannot assign them each an ID.

    So this is how I did it:

    I had to add a background rectangle with id bg so that the layer was clickable:

    var bg = new Kinetic.Rect({
        width: stage.getWidth(),
        height: stage.getHeight(),
        x: 0,
        y: 0,
        id: 'bg'
    });
    
    layer.add(bg);
    

    Now the layer can be clicked and we can select the targetNode:

    layer.on('mousedown', function (e) {
        var node = e.targetNode;
        select(node);
    });
    
    function select(node) {
        deselect();
    
        if (node.parent.nodeType = 'Kinetic.Group') {
            var children = node.parent.children;
            for (i = 1; i < children.length; i++) {
                if (children[i].getName() == 'topLeft' ||
                    children[i].getName() == 'topRight' ||
                    children[i].getName() == 'bottomRight' ||
                    children[i].getName() == 'bottomLeft') {
                    children[i].show();
    
                }
            }
        }
    }
    
    function deselect() {
        var children = layer.children;
    
        for (i = 1; i < children.length; i++) {
            var grandChildren = children[i].children;
    
            if (grandChildren) {
                for (j = 1; j < grandChildren.length; j++) {
                    if (grandChildren[j].getName() == 'topLeft' ||
                        grandChildren[j].getName() == 'topRight' ||
                        grandChildren[j].getName() == 'bottomRight' ||
                        grandChildren[j].getName() == 'bottomLeft') {
                        grandChildren[j].hide();
                        layer.draw();
                    }
                }
            }
        }
    }
    

    On select, we deselect everything and then we find the anchors IF the node we clicked on is a group (containing a shape and the anchors). We don't want to select any anchors if we click on the bg

    Here's the jsFiddle

    Also note: I hid the anchors once they were added to the group, that's why no anchors are shown on init.

    Edit: i=1 and j=1 because the image is the first child inside the group, and the anchors follow.

    0 讨论(0)
提交回复
热议问题