在KineticJS中创建具有不同图层形状的组

时间:2013-10-25 14:01:41

标签: javascript kineticjs

我会尽可能准确地解释我的问题。

我的项目有2组([Group1],[Group2]) 我想要[Button],它可以切换[Group1]的可见性。 (setOpacity为1或0) 我希望[Group1],[Group2]可以拖动并相互固定。

I've tried this way:
I've created 2 layers [Layer1] and [Layer2].
I've added [Group1] to [Layer1]
I've added [Group2] to [Layer2]
When i click [Button], i toggle Opacity of [Layer1]
I've created [MainGroup] and set it to draggable.
I've added [Group1,2] to [MainGroup]. To make them anchored to each other, and i could drag them.

但如果我使用[Group1] .getParent()我得到[Layer1],而不是MainGroup,为什么呢?我应该使用不同的逻辑吗?我需要[Group1] .getParent()来返回[MainGroup],所以我可以在其中找到另一个组,即[Group2]并为其添加一些形状。

我的KineticJS版本是:4.7.2

1 个答案:

答案 0 :(得分:0)

您可以嵌套这样的组:http://jsfiddle.net/m1erickson/YmAdJ/

  • 在图层上创建一个containerGroup。
  • 创建Group1并将其添加到containerGroup。
  • 创建Group2并将其添加到containerGroup。
  • 使containerGroup可拖动。

嵌套组看起来像这样:

// make a container group to hold group1 and group2

var containerGroup=new Kinetic.Group({
    x:20,
    y:20,
    width:225,
    height:100,
    draggable:true
});
layer.add(containerGroup);

// create group1 and group2 inside containerGroup

var group1=new Kinetic.Group({
    id:"g1",
    x:0,
    y:0,
    width:125,
    height:100,
});
containerGroup.add(group1);

var group2=new Kinetic.Group({
    id:"g2",
    x:126,
    y:0,
    width:100,
    height:100,
});
containerGroup.add(group2);

对于Group1和& Group2,您可以像这样获得对containerGroup的引用:

group1.on(“click”,function(){
      var myContainerGroup=this.getParent();
});

group2.on(“click”,function(){
      var myContainerGroup=this.getParent();
});

您可以使用对containerGroup的引用来获取对这样的子组的引用:

var myGroup1 = myContainerGroup.get("#g1")[0];

var myGroup2 = myContainerGroup.get("#g2")[0];