Fabric.js: can't remove objects while iterating over the getObjects() table

Created on 2 Apr 2012  Â·  6Comments  Â·  Source: fabricjs/fabric.js

the following code:

var obj = canvas.getObjects();
$.each(obj, function(i,val){
canvas.remove(val);
}

doesn't clear entire canvas.

bug

Most helpful comment

@amitgaur208 is right. It's an array iteration issue. This code is working pretty well for me.

var arrObj = canvas.getObjects();
while(arrObj.length != 0){
  arrObj[0].remove();
}

All 6 comments

I'll see what's going on later. Meanwhile, you can use canvas.clear().

hi,

of course I can use canvas.clear(), and so I did.

However, this issue is a bit disturbing, because it can be hard to spot in more complex cases.

Cheers,
Radek

Dnia 2 kwietnia 2012 17:11 Juriy Zaytsev [email protected] napisaÅ‚(a):

I'll see what's going on later. Meanwhile, you can use canvas.clear().


Reply to this email directly or view it on GitHub:
https://github.com/kangax/fabric.js/issues/148#issuecomment-4880420

Absolutely. This looks like a regression, actually. I know that this was definitely working before. I'll fix soon.

Looking closer into it, I realized that this has nothing to do with fabric. You see, since canvas.remove() modifies canvas' objects array (the one that's returned from canvas.getObjects()), forEach becomes unreliable as array's length does not stay the same during the loop.

You can see people running into similar problem online, when using Array::splice (what canvas.remove() depends on). Here's one example (and explanation) — http://stackoverflow.com/a/9105729/130652

Its' not fabric JS issue, but its array iteration issue.

@amitgaur208 is right. It's an array iteration issue. This code is working pretty well for me.

var arrObj = canvas.getObjects();
while(arrObj.length != 0){
  arrObj[0].remove();
}
Was this page helpful?
0 / 5 - 0 ratings