Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FabricJS: using object controls on canvas to resize, but not scale

The problem is to update the actual object.width, object.height and keep object.scaleX = 1 and object.scaleY = 1 when using the visual controls on the canvas.

The origin of the problem is when manipulating the object using controls, fabric.js changes the scale of the object, as well as scaling the stroke of paths, which I would like to be of the same width always.

So I would like to make it more like Adobe Illustrator-like, and not scale the width of the stroke along with the width of the rectalngular, for example.

like image 476
Alexander Titov Avatar asked Dec 02 '22 14:12

Alexander Titov


2 Answers

I have found a solution to a question formulated in a different manner here:

Rect with stroke, the stroke line is mis-transformed when scaled

The idea is to calculate the new would-be width and height using the new scale factors, set the new dimensions and reset the scale factors to 1.

Here's the code example from that answer:

el.on({
'scaling': function(e) {
    var obj = this,
        w = obj.width * obj.scaleX,
        h = obj.height * obj.scaleY,
        s = obj.strokeWidth;

    obj.set({
        'height'     : h,
        'width'      : w,
        'scaleX'     : 1,
        'scaleY'     : 1
    });
}
});
like image 180
Alexander Titov Avatar answered Dec 04 '22 04:12

Alexander Titov


From Fabric.js version 2.7.0 you can enable a strokeUniform property on the object this will always match the exact pixel size entered for stroke width.

var circle2 = new fabric.Circle({
    radius: 65,
    fill: '#4FC3F7',
    left: 110,
    opacity: 0.7,
    stroke: 'blue',
    strokeWidth: 3,
    strokeUniform: true
});

http://fabricjs.com/stroke-uniform

like image 36
qorsmond Avatar answered Dec 04 '22 03:12

qorsmond