2016-11-11 23 views
0

我想使網格變得可選。我有以下用於生成網格的方法:FabricJS渲染後,組和控制框的位置不對

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

正如您所看到的,我在創建組時設置了四個屬性。問題在於團隊呈現錯誤的立場。它有一些偏移量。但是,如果我刪除widthheight創建對象時,則組具有合適的位置,但我無法選擇它,因爲widthheight爲零。這是一個DEMO,運行它並嘗試選擇網格,您將看到偏移量。然後,評論widthheight看到的差異。

如何解決?

PS。我試圖用setCoords的方法,但沒有幫助。

回答

2

您可以先創建線路修復它,然後創建包含傳遞給行引用數組組:

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

在這裏看到:http://jsfiddle.net/pevtwgcL/2/

+0

非常感謝你。 – user348173

+0

你知道爲什麼它發生在我的代碼?我在問,因爲在向現有組添加新形狀時,我遇到同樣的問題?例如,我們有添加矩形到所選組的按鈕:'var newRect = new fabric.Rect({...}};''selectedGroup.add(newRect)' – user348173

+0

請使用'addWithUpdate()'而不是'add ()',像這樣:'selectedGroup.addWithUpdate(newRect)'。 – janusz