2015-10-12 77 views
-1

我想切換(意味着渲染所有矩形,然後刪除所有)。 這裏是我的代碼片段:如何切換Fabricjs中的矩形或圓形?

// CWC is current working canvas. 
console.log("Toggling Shapes's" + UIConstants.CWC); 
// locate CWC. 
var objects = UIConstants.CWC.getObjects(); 
var ShapesObjects = UIConstants.ShapesArray; 
// check if array is empty 
if (objects.length < 2) { 
    // iterating from 2 because 1st object is image. 
    // add Shapes from toggle array and make toggle array as empty. 
    if (ShapesObjects.length > 0) { 
     for (var idx = 0; idx < ShapesObjects.length; idx++) { 
      UIConstants.CWC.add(ShapesObjects[idx]); 
     } 
    } 
} else { 
    // remove all Shapes and add to toggle array. 
    for (var idx = 1; idx < objects.length; idx++) { 
     ShapesObjects.push(objects[idx]); 
     // remove all previous handlers. 
     try { 
      UIConstants.CWC.setActiveObject(objects[idx]); 
      UIConstants.CWC.remove(UIConstants.CWC.getActiveObject()); 
     } catch (E) { 
     } 
    } 
} 

不過,我得到這個爲前4次點擊運行後,它並沒有爲3-4次點擊工作,然後再工作。 我的錯誤是什麼?

回答

1

使用while循環而不是for循環。 即改變 for (var idx = 1; idx < objects.length; idx++) { ShapesObjects.push(objects[idx]); // remove all previous handlers. try { UIConstants.CWC.setActiveObject(objects[idx]); UIConstants.CWC.remove(UIConstants.CWC.getActiveObject()); } catch (E) { } }

成爲 while (objects.length > 1) { // iterating from 2nd Index because 1st Index is image. UIConstants.ROIArray.push(objects[1]); //remove all previous handlers. try { UIConstants.CWC.setActiveObject(objects[1]); UIConstants.CWC.remove(UIConstants.CWC.getActiveObject()); } catch(E) { console.log(E); break; } }