如何在Fabricjs中切换矩形或圆?

时间:2015-10-12 13:37:27

标签: javascript jquery html5-canvas 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 个答案:

答案 0 :(得分: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; } }