Skip to content Skip to sidebar Skip to footer

Confusion About Group Capabilities Of Fabricjs

I have been experimenting with fabricjs lately. I am attempting to create a group structure (hierarchy) of layers similar to a raster editor like krita/gimp, conceptually. In other

Solution 1:

group#addWithUpdate will update dimension and position. Just call add while adding to group, after adding the objects call group.addWithUpdate() to update the dimension.

DEMO

var canvas = new fabric.Canvas("t2", {
  // preserveObjectStacking : true,width: 130,
  height:130
});

var rect1 = new fabric.Rect({
  'top': 0,
  'left': 0,
  'width': 30,
  'height': 30,
  'fill': 'red'
})

var rect2 = new fabric.Rect({
  'top': 0,
  'left': 0,
  'width': 30,
  'height': 30,
  'fill': 'yellow'
})

// contains groups 2 and 3// modifying "top" and "left" seems to have no effect?var group1 = new fabric.Group([], {
  'top': 50,
  'left': 20,
})

//will contain rect1 (red)var group2 = new fabric.Group([], {
  'top': 0,
  'left': 0,
})

// will contain rect2 (yellow)var group3 = new fabric.Group([], {
  'top': 0,
  'left': 0,
})
canvas.add(group1)

group1.add(group2)
group2.addWithUpdate(rect1)

group1.add(group3)
group3.addWithUpdate(rect2)
group1.addWithUpdate()
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.js"></script><divid="t2-cont" ><canvasid="t2"style="border:black solid 2px;"></canvas></div>

And to change the positions of object call moveTo on grouped object.

DEMO

const canvas = new fabric.Canvas("t2", {
  // preserveObjectStacking : true,width: 130,
  height:130
});

const rect1 = new fabric.Rect({
  'top': 0,
  'left': 0,
  'width': 30,
  'height': 30,
  'fill': 'red'
})

const rect2 = new fabric.Rect({
  'top': 0,
  'left': 0,
  'width': 30,
  'height': 30,
  'fill': 'yellow'
})

// contains groups 2 and 3// modifying "top" and "left" seems to have no effect?const group1 = new fabric.Group([], {
  'top': 50,
  'left': 20,
})

//will contain rect1 (red)const group2 = new fabric.Group([], {
  'top': 0,
  'left': 0,
})

// will contain rect2 (yellow)const group3 = new fabric.Group([], {
  'top': 0,
  'left': 0,
})
canvas.add(group1)

group1.add(group2)
group2.addWithUpdate(rect1)

group1.add(group3)
group3.addWithUpdate(rect2)
group1.addWithUpdate()

setTimeout(()=> {
  group2.moveTo(1);
  group1.addWithUpdate();
  canvas.requestRenderAll();
}, 1000)
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.js"></script><divid="t2-cont" ><canvasid="t2"style="border:black solid 2px;"></canvas></div>

Post a Comment for "Confusion About Group Capabilities Of Fabricjs"