user348173
user348173

Reputation: 9278

FabricJS After rendering, group and control box have wrong position

I want to make grid and make it selectable. I have the following method for generating grid:

function getGrid(width, height, count, name) {

        var oGridGroup = new fabric.Group([], {left: 0, top: 0, width: width, height: height, selection: true});
        var gridCountCell = count || 5;

        gridSizeWidth = width / gridCountCell - 0.3;
        gridSizeHeight = height / gridCountCell - 0.3;
        var lineOption = {stroke: '#ccc', strokeWidth: 1};

        for (var i = Math.ceil(width / gridSizeWidth); i--;) {           
            oGridGroup.add(new fabric.Line([gridSizeWidth * i, 0, gridSizeWidth * i, height], lineOption));
        }
        for (var i = Math.ceil(height / gridSizeHeight); i--;) { 
            oGridGroup.add(new fabric.Line([0, gridSizeHeight * i, width, gridSizeHeight * i], lineOption));
        }
        if(name) {
            oGridGroup.set({name: name})
        }

        return oGridGroup;
    }

As you can see, I setup four properties when create group. The problem is the group is rendered in wrong position. It has some offset.But, if I delete width and height when create object then group has proper position, but I can't select it, because width and height are zero. This is a DEMO, run it and try to select grid, you will see the offset. Then, comment width and height to see difference.

How to fix it?

PS. I tried to use setCoords method, but didn't help.

Upvotes: 0

Views: 1376

Answers (1)

janusz
janusz

Reputation: 848

You can fix it by creating the lines first, then create a group passing an array containing the references to the lines:

var lines = [];
for (var i = Math.ceil(width / gridSizeWidth); i--;) {           
  lines.push(new fabric.Line([gridSizeWidth * i, 0, gridSizeWidth * i, height], lineOption));
}
for (var i = Math.ceil(height / gridSizeHeight); i--;) { 
  lines.push(new fabric.Line([0, gridSizeHeight * i, width, gridSizeHeight * i], lineOption));
}               
var oGridGroup = new fabric.Group(lines, {left: 0, top: 0, width: width, height: height, selection: true});

See here: http://jsfiddle.net/pevtwgcL/2/

Upvotes: 2

Related Questions