yogeshwari
yogeshwari

Reputation: 153

Fabric js:To make group of all objects

Is it possible in fabric js, on click event to make group of all the object present on canvas

Upvotes: 2

Views: 12651

Answers (1)

Theo Itzaris
Theo Itzaris

Reputation: 4671

yes, it is possible to group all the canvas objects on click event. below i show you an example that creates three objects and group them on click.

var canvas = new fabric.Canvas('c');
canvas.backgroundColor = 'yellow';

//create circle object
 var circle = new fabric.Circle({
                  radius: 20, 
                  fill: 'red', 
                  left: 100, 
                  top: 100
                });
            canvas.add(circle);


//create square object
var square = new fabric.Rect({
              left: 130, 
              top: 140,
              fill: 'green',
              width: 40,
              height: 80
            });
            canvas.add(square);

canvas.renderAll();


$('#groupthem').on('click', function(event) {
    groupthem();
 });


var site_url =  'http://fabricjs.com/assets/1.svg';

fabric.loadSVGFromURL(site_url, function(objects) { 
          var group = new fabric.PathGroup(objects, { 
          left: 165, 
          top: 100, 
          width: 295, 
          height: 211 
        }); 
        canvas.add(group); 
        canvas.renderAll(); 
          }); 


function groupthem (){

    var objs = [];
    //get all the objects into an array
    objs = canvas._objects.filter(function(obj){
        return obj;
    });

    //group all the objects 
     var alltogetherObj = new fabric.Group(objs,{
                top:200,left:250,
                originX:'center',
                originY:'center'});


    //clear previous objects
    canvas._objects.forEach(function(obj){
        obj.remove();
    });

    canvas.add(alltogetherObj);
    alltogether.setCoords(); 
    canvas.renderAll();
}

live jsfiddle : http://jsfiddle.net/tornado1979/y6fqj8go/

enter image description here

hope helps, good luck.

New updated fiddler link:http://jsfiddle.net/yogeshwari/sezxhqc4/1/

Upvotes: 5

Related Questions