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

六月ゝ 毕业季﹏ 提交于 2019-12-02 09:32:34

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!