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

与世无争的帅哥 提交于 2019-11-30 14:41:39
arty

First of all you have miss-typed the name of the property in your fiddle : strokWidth - e is missing. But this is not the cause of the problem since the default value for the strokeWidth is 1.

The scaled stroke issue is the expected behavior and what you ask to do is not. Anyway, before you check my code, read here and here and maybe some more here.

Then try this code to help with your needs, this will work perfectly only if you keep the scale ratio of your rectangle as 1:1 (scaleX = scaleY).

This is jsfiddle:

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

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

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

canvas.add (el);
canvas.renderAll ();

This can be done so that you can scale independently.

In the scaling event check the width, height and scale factors, set the height and width to the new effective values and reset the scaleX and scaleY.

This quite probably will break other things that are scaled with the object so you'd have to handle those attributes in a similar fashion.

Demo Fiddle.

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

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

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
        });
    }
});

canvas.add (el);
canvas.renderAll ();

Fabricjs now has a strokeUniform property on fabric.Rect that can be used to prevent the stroke width from mis-transforming.

When you set strokeUniform to false it will scale with the object if true it will match the pixel size of the stroke width.

var el = new fabric.Rect({
    originX: "left",
    originY: "top",
    left: 5,
    top: 5,
    stroke: "#ccc",
    strokWidth: 1,
    fill: 'transparent',
    opacity: 1,
    width: 200,
    height: 200,
    cornerSize: 6,
    strokeUniform: true
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!