2

My objective in this jsfiddle is to have a Fabric object (for example, a rect) that will "visually" keep its original border width even when it is scaled/expanded. For example, let's say that strokeWidth = 3px; usually when a rect is expanded the user will see the border wider. In my case I need the border to keep its width in screen pixels.

To achieve that, I calculate a factor factorHeight = origHeight / obj.getHeight() every time the object is scaled, and multiply strokeWidth by this factor. This works well when the object is scaled proportionally (try it in the jsfiddle).

However, when the object is not scaled proportionally, the problem is that the top/bottom border widths are different from the right/left border widths. Since there's a single strokeWidth for all these borders I cannot change this behavior. Any ideas?

Javascript:

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

var origWidth = 40;
var origHeight = 100;
var origStrokeWidth = 3;

var rect = new fabric.Rect({ 
    top: 30,
    left: 30,
    width: origWidth,
    height: origHeight,
    fill: 'rgba(255,255,255,0)',
    strokeWidth: origStrokeWidth,
    stroke: '#000000' 
});
canvas.add(rect);

canvas.on('object:scaling', onObjectScaled);

function onObjectScaled(e) {
    var obj = e.target;

    var factorHeight = origHeight / obj.getHeight();
    var factorWidth = origWidth / obj.getWidth();
    var factor;
    if (factorHeight < factorWidth)
        factor = factorHeight;
    else
        factor = factorWidth;
    var newStrokeWidth = origStrokeWidth * factor;

    obj.setStrokeWidth(newStrokeWidth);
    canvas.renderAll();
}
ps0604
  • 1,227
  • 23
  • 133
  • 330
  • Would like an answer too. – Matthew Cornell Jul 13 '15 at 18:33
  • Possible duplicate of [Fabricjs How to scale object but keep the border (stroke) width fixed](https://stackoverflow.com/questions/39548747/fabricjs-how-to-scale-object-but-keep-the-border-stroke-width-fixed) – smnbbrv Sep 12 '17 at 12:52

1 Answers1

0

I had the same problem, this is the solution I found somewhere here on SO, but I cant provide you with the link to question, but here is the code that solved it:

canvas.on({
    'object:scaling': function(e) {
    var obj = e.target;
    obj.KeepStrokeWidth = 5;
    if(obj.KeepStrokeWidth){
        var newStrokeWidth = obj.KeepStrokeWidth / ((obj.scaleX + obj.scaleY) / 2);
        obj.set('strokeWidth',newStrokeWidth);
        }
      }
    });

Hope it will work for you too.

Lasto
  • 107
  • 8
  • It's similar to my solution, the problem is that when you set `obj.setStrokeWidth(newStrokeWidth);` the top and bottom borders are **still** different from the left and right borders – ps0604 Apr 02 '15 at 12:45