maintain stroke and text size

resizing and maintain text size and border size

by 20yco

HTML

<canvas id="c1" width="600" height="500" style="border:1px solid #ccc"></canvas>

CSS

body{
    background-color:white;
}

JavaScript

var canvas = new fabric.Canvas("c1");


reinit()
canvas.on({
    'object:scaling': function(e) {
    	
        var obj = e.target,
            w = obj.width * obj.scaleX,
            h = obj.height * obj.scaleY,
            s = obj.strokeWidth;
            
        console.log(obj.width, obj.scaleX, h,w,s)
		
        obj._objects[0].set({
            'height'     : obj.height,
            'width'      : obj.width,
            'scaleX'     : 1,
            'scaleY'     : 1,
            h: h,
            w: w
            //top: 1,
            //left: 1,
        });
        
        /*e.target.set({
            'height'     : h,
            'width'      : w,
            'scaleX'     : 1,
            'scaleY'     : 1
        });*/
    }
});

canvas.on({
    'object:modified': function(e) {
    console.log(e)
    //e.target.set({scaleX:1, scaleY:1})
    	group = e.target
    	rect = e.target._objects[0]
      rect.set({height:rect.h, width: rect.w})
      console.log('r',rect.width, group.width)
      text = group._objects[1]
      canvas.remove(group)
      canvas.add(new fabric.Group([rect,text], {
      	top: group.top,
        left: group.left
      }))
    }

});

function reinit(){
	var el = new fabric.Rect({
    originX: "left",
    originY: "top",
    
    stroke: "rgb(0,0,0)",
    strokeWidth: 1,
    fill: 'transparent',
    opacity: 1,
    width: 200,
    height: 200,
    cornerSize: 6
	});

  var text = new fabric.IText('test', {  fontSize: 16});

  var group = new fabric.Group([ el, text ], {
     width: 200,
     height: 200,
     left: 5,
     top: 5,
  });
  canvas.add(group);
	canvas.renderAll();

}