How to add objects in group dynamically in fabric

2019-08-08 15:42发布

1.I want to add objects dynamically in group, or cloning object dynamically. 2.I have tried but not working in looping. 3.Want to make group of objects present over canvas (which is dragged by user over canvas)

 <script src="js/fabric.js" type="text/javascript"></script>
    <canvas id="canvas" class="canvas" ></canvas>

    <style>
    .canvas {
    border: 1px solid Black;
    width: 1100px;
    height: 1100px;
    }

    </style>

     <script>
        var canvas = new fabric.Canvas('canvas');
   canvas.setWidth(1100);
  canvas.setHeight(1100);



// clear canvas
  canvas.clear();

  // add red rectangl
  canvas.add(new fabric.Rect({
  width: 50, height: 50, left: 50, top: 50, fill: 'rgb(255,0,0)'
}));

  canvas.add(new fabric.Rect({
  width: 50, height: 50, left: 110, top: 50, fill: 'rgb(255,0,0)'
  }));
  canvas.add(new fabric.Rect({
  width: 50, height: 50, left: 170, top: 50, fill: 'rgb(285,0,0)'
  }));


//var clone = obj.clone();
//alert(obj);

items = canvas._objects;

var group = new fabric.Group([
     // canvas.add(obj)
  canvas.items.clone()
//  canvas.item(1).clone(),
//  canvas.item(2).clone()
]);


canvas.clear().renderAll();
canvas.add(group);




    </script>

1条回答
小情绪 Triste *
2楼-- · 2019-08-08 16:40

Not sure but I think you are looking for addWithUpdate

Code:

group.addWithUpdate(new fabric.Rect({
      ...

    }));

for more see this http://fabricjs.com/fabric-intro-part-3/

查看更多
登录 后发表回答