Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fabricjs group inside another group

I have problem with groups in FabricJS. When I add eg. 2 groups inside another group, I can't properly set left and top property for internal groups. Look at my code.

Letter A should be on the top left corner (top: 0, left: 0), and letter B should be below A (top: 50, left: 50).

But in this example letters are on the middle, and when I changing postion of B, position A changing too.

Is it bug in FabricJS?

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

function getCell(contentTxt, fontSize, leftOffset, topOffset) {
        var cellCnt = new fabric.Text(contentTxt, {
            fontSize: fontSize
        });

        var cellGrp = new fabric.Group([cellCnt], {
            height: 50,
            width: 50,
            top: topOffset,
            left: leftOffset
        });

        return cellGrp;
    }
    
    var cellsArray = [];

    //It should be on top left corner
    cellsArray.push(
            getCell('A', 30,
                    0, 0));

        
    cellsArray.push(
            getCell('B', 30,
                    50, 50));

    var rowGrp = new fabric.Group(cellsArray, {
        height: 200,
        width: 200
    });

canvas.add(rowGrp);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<canvas id="editorCnvs" width="400" height="566">
</canvas>
like image 746
Jacek Gzel Avatar asked Dec 17 '25 21:12

Jacek Gzel


1 Answers

Group set its dimension automatically after calculating a bounding box that can catch all elements.

objects in the group are positioned relative to center.

If you set width and height you will obtain the effect that the extra width or height is spread around objects.

If you create the groups without width and height you will see that the position are respected.

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

function getCell(contentTxt, fontSize, leftOffset, topOffset) {
        var cellCnt = new fabric.Text(contentTxt, {
            fontSize: fontSize
        });

        var cellGrp = new fabric.Group([cellCnt], {

            top: topOffset,
            left: leftOffset
        });

        return cellGrp;
    }
    
    var cellsArray = [];

    //It should be on top left corner
    cellsArray.push(
            getCell('A', 30,
                    0, 0));

        
    cellsArray.push(
            getCell('B', 30,
                    50, 50));

    var rowGrp = new fabric.Group(cellsArray, {

    });

canvas.add(rowGrp);
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.5.0/fabric.min.js"></script>
<canvas id="editorCnvs" width="400" height="566">
</canvas>
like image 140
AndreaBogazzi Avatar answered Dec 19 '25 13:12

AndreaBogazzi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!