Skip to content
Advertisement

fabricjs How can i keep fixed size on group elements while others scaling?

Hello I use fabricjs to play with the html canvas. I create the canvas and i add group of objects on it.

On a group of objects, I need to keep fixed width & height for some objects while I scale the object.

I use the ‘object:scaling’ event to get the active object when it changes size, I read each object of the group and I assign element[i].set({‘radius’:5}) on the group objects that I want to be unchanged.

But the result is that , all the group object to resize.

I show you the snippet of the object:scaling event :

 canvas.on('object:scaling',function(e){

        var activeObject1 = e.target;

        var elements = e.target._objects;

          var count_elements =  elements.length;


            for(var i = 0; i < count_elements; i++) {

                var type = elements[i].typeCircle;

                if(type == "parts"){
                                      //elements[i].set({"radius":8,"fill":"#abcde2","stroke":"#367827"});
                    //elements[i].set('radius',8);
                    /*elements[i].setWidth(16);
                    elements[i].setHeight(16);
                    elements[i].currentWidth = 16;
                    elements[i].currentHeight = 16;
                    elements[i].scaleX = 1;
                    elements[i].scaleY = 1;
                    console.log(elements[i]);
                    canvas.renderAll();*/
                }
              }
         });

What should I write into the for loop to keep fixed size on some objects? everything that I used above, they don’t work except for the “fill”:”#abcde2″,”stroke”:”#367827″

If anyone has faced something similar on fabricjs, please let me know .

Advertisement

Answer

You must use setScaleX() and setScaleY() methods. Here is an example…

var Rect = new fabric.Rect({
  width: 200,
  height: 200,
  top: 100,
  left: 100,
  fill: 'rgba(255,0,0,0.5)',
  stroke: '#000',
  strokeWidth: 1,
});

var Circle = new fabric.Circle({
  left: 100,
  top: 100,
  fill: '#FF00FF',
  stroke: 'red',
  radius: 100,
  opacity: 1,
});

var Group = new fabric.Group([Rect, Circle])
canvas.add(Group)
canvas.on({
  'object:scaling': onChange
})

function onChange(obj) {
    var circle = obj.target.item(1),
        group = obj.target,
        scaleX = circle.width / group.getWidth(),
        scaleY = circle.height / group.getHeight();
    circle.setScaleX(scaleX);
    circle.setScaleY(scaleY);

}

JSFIDDLE

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement