I have two groups (group1, group2) which both contain rectangles. Each of these groups is draggable. When I move a shape (group or rectangle in my case) and it overlaps with the other I trigger an event and add these two groups to another group (a super group) one which will be also draggable. The way I am doing this right now is by creating a supergroup which contains both groups as follows:
group1.add(cube1);
group2.add(cube2);
superGroup.add(group1);
superGroup.add(group2);
Even though this seems to work for the simple case of adding, for more complex cases this becomes cumbersome and inefficient.
So my question is:
Is there any other way of grouping shapes rather than by adding it to a group?
Instead of creating a third superGroup, how about merging group1 into group2 (or visa-versa).
This could be accomplished by adjusting the x/y of all group1 children and then moving them to group2.
Example code and a Demo: http://jsfiddle.net/m1erickson/BkfkC/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Prototype</title>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script src="http://d3lp1msu2r81bx.cloudfront.net/kjs/js/lib/kinetic-v5.0.1.min.js"></script>
<style>
body{padding:20px;}
#container{
border:solid 1px #ccc;
margin-top: 10px;
width:350px;
height:350px;
}
</style>
<script>
$(function(){
var stage = new Kinetic.Stage({
container: 'container',
width: 350,
height: 350
});
var layer = new Kinetic.Layer();
stage.add(layer);
var g1=new Kinetic.Group({x:10,y:10,draggable:true});layer.add(g1);
var g2=new Kinetic.Group({x:60,y:60,draggable:true});layer.add(g2);
var circle1a = new Kinetic.Circle({
x:20,
y:20,
radius: 30,
fill: 'red',
stroke: 'black',
strokeWidth: 4,
});
g1.add(circle1a);
var circle1b = new Kinetic.Circle({
x:120,
y:120,
radius: 30,
fill: 'green',
stroke: 'black',
strokeWidth: 4,
});
g1.add(circle1b);
var circle2 = new Kinetic.Circle({
x:20,
y:20,
radius: 30,
fill: 'blue',
stroke: 'black',
strokeWidth: 4,
});
g2.add(circle2);
layer.draw();
function mergeG1intoG2(g1,g2){
var g2pos=g2.position();
var g1Children=g1.getChildren();
n=g1Children.length-1;
while(n>=0){
var child=g1Children[n--];
var pos=child.getAbsolutePosition();
child.x(pos.x-g2pos.x);
child.y(pos.y-g2pos.y);
child.moveTo(g2);
};
g1.destroy();
layer.draw();
}
$("#myButton").click(function(){
mergeG1intoG2(g1,g2);
});
}); // end $(function(){});
</script>
</head>
<body>
<button id="myButton">Merge red+green group into blue group</button>
<div id="container"></div>
</body>
</html>