Reputation: 535
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:
https://i.sstatic.net/yYnFR.jpg
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:
https://i.sstatic.net/G0eBu.jpg
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
Upvotes: 3
Views: 10241
Reputation: 32859
You could use the following function to remove all the grids ...
function RemoveGrid() {
var objects = canvas.getObjects('line');
for (let i in objects) {
canvas.remove(objects[i]);
}
RenderCanvas();
}
ᴅᴇᴍᴏ
var canvas = new fabric.Canvas('c');
var grid = 30;
var cWidth = canvas.getWidth();
// add grid
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
}));
}
}
// remove grid
function RemoveGrid() {
var objects = canvas.getObjects('line');
for (let i in objects) {
canvas.remove(objects[i]);
}
RenderCanvas();
}
canvas {border: 1px solid #999}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.7.11/fabric.min.js"></script>
<button onclick="CanvasGrid()">Add Grid</button>
<button onclick="RemoveGrid()">Remove Grid</button>
<canvas id="c" width="300" height="300"></canvas>
Upvotes: 9