fabricjs removing objects (line) from canvas but not all objects are getting removed

Viewed 9679

I am relatively new to fabricjs. I am creating a grid on the canvas with fabricjs(1.7.11),

What I am trying to achieve:

basically, when I click a button a grid is created and when I click another button I want to delete the grid ( the grid is made of fabricjs lines) but for some reason, not all lines are getting removed.

function to create the grid

var grid = 30;
var cWidth = canvas.getWidth();

function CanvasGrid(){
    for(var i = 0; i < (cWidth / grid); i++){
        canvas.add(new fabric.Line([i * grid, 0, i * grid, cWidth], {
            stroke: '#ccc',
            selectable: false
        }));

        canvas.add(new fabric.Line([0, i * grid, cWidth, i * grid], {
            stroke: '#ccc',
            selectable: false
        }));
    }
}

Created grid on canvas:

http://imgur.com/a/U1bD7

function to delete grid:

function RemoveGrid(){
    var objects = canvas.getObjects('line');
    for(var i = 0; i < objects.length; i++){
        canvas.item(i).remove();        
    }   
    RenderCanvas();
}

Result:

http://imgur.com/a/vPmMa

I want to remove the rest of the lines. Any help much appreciated.

Thank you.

edit: I tried this solution but I have to keep clicking on the button till all lines are removed.

function RemoveGrid(){
    canvas.forEachObject(function(obj){
        if(obj.type === 'line'){
            obj.remove();
        }
    });

    RenderCanvas();
}

Any help much appreciated. Thanks

1 Answers
Related