1

I am new to fabric js. i am trying to left align all the objects in a group by using this function.

$rootScope.alignLeft = function () {
    var activeObject = canvas.pages[canvas.activePageIndex].fabric.getActiveObject();
    if (activeObject.type == "group") {
        var items = activeObject._objects;
        var left = activeObject.getLeft();
        var top = activeObject.getTop();
        console.log(activeObject);
        canvas.pages[canvas.activePageIndex].fabric.remove(activeObject);
        console.log(left);
        console.log(top);
        for (var i = 0; i < items.length; i++) {
            canvas.pages[canvas.activePageIndex].fabric.add(items[i].set({left: activeObject.left}));
        }

        canvas.pages[canvas.activePageIndex].fabric.renderAll();
    }
};

The problems that i am facing are

1)if i dont use .remove(activeGroup) it makes a duplicate of the objects in the group. I want to keep the activeGroup and somehow stop it from duplicating itself.

2) The items[i].set({left : activeObject.left} correctly sets the left alignment but the objects top value changes and i don't want that. i have tried to use items[i].set({left : activeObject.left,top:activeObject.top}); but failed to keep it constant.

How can i achieve this functionality?

Alexander Reznikov
  • 1,266
  • 1
  • 14
  • 23
umair.ashfr
  • 1,171
  • 13
  • 32

1 Answers1

0

How i was able to solve these problems. I am sure future newbie's to fabricjs like me will face these basic conceptual problems just like me.

Answers to points 1&2:

1) I used .remove(activeGroup) to remove it and made a new group and added items inside activeGroup into group.

2) Here are some links that really helped me understand the positioning system used in fabricjs stackOverflow link Github link

$rootScope.alignLeft = function(){
            

            var activeObject = canvas.pages[canvas.activePageIndex].fabric.getActiveObject();
            var group = new fabric.Group();
            if(activeObject.type=="group"){
                var items = activeObject._objects;
                canvas.pages[canvas.activePageIndex].fabric.remove(activeObject);
                for(var i = 0;i<items.length;i++){
                    var ObjTop = activeObject.top + items[i].top + activeObject.height/2 ;
                    items[i].set({left :activeObject.left,top:ObjTop});
                    group.addWithUpdate(activeObject.item(i));

                }
                canvas.pages[canvas.activePageIndex].fabric.add(group);
                canvas.pages[canvas.activePageIndex].fabric.setActiveObject(group);
                canvas.pages[canvas.activePageIndex].fabric.renderAll();

            }


        }
Community
  • 1
  • 1
umair.ashfr
  • 1,171
  • 13
  • 32