如何在fabric js中动态添加组中的对象

时间:2015-11-17 07:23:04

标签: javascript html5-canvas fabricjs

1.我想在组中动态添加对象,或动态克隆对象。 我试过但没有在循环中工作。 3.想要在画布上显示一组对象(由用户在画布上拖动)

 <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 个答案:

答案 0 :(得分:6)

不确定,但我认为您正在寻找addWithUpdate

代码:

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

    }));

了解更多信息,请参阅此http://fabricjs.com/fabric-intro-part-3/