Reputation: 3517
I'm receiving this error after attempting to optimise some code I'm working on.
Initially I was using canvas.forEachObject(function(obj){})
which was working fine but I needed to streamline the process somewhat.
I now have a function that iterates through the canvas and adds all the relevant object type to an array that I will then use.
function getObjects(){
var canvasObjects = canvas.getObjects();
var theArray = new Array();
for(obj in canvasObjects){
if(canvasObjects[obj].get('type') == 'thisType'){
theArray.push(canvasObjects[obj]);
}
if(canvasObjects[obj].get('type') == 'group'){
var groupObjects = canvasObjects[obj].getObjects();
for(groupObj in groupObjects){
if(groupObjects[groupObj].get('type') == 'thisType'){
theArray.push(groupObjects[groupObj]);
}
}
}
}
return theArray;
}
I'm then calling a function in an animation loop that uses the array in order to determine if a collision has occurred.
Array created here:
var geoArray = getObjects();
function detectCollision(target) {
target.setCoords();
geoArray.forEachObject(function(obj)
//for(obj in geoArray) //1st attempt - same result
{
obj.setCoords();
if(obj!=target && target.intersectsWithObject(obj)){
//..do stuff
}
});
}
The array is built fine and contains the correct number of objects so I'm sure there is no problem there. The problem occurs when I run the collision function and the type error problem occurs. Searching indicates that I may not be returning the object type but I'm not sure if this is the case and if so I'm not sure how to fix it.
Many thanks for any help.
Edit: the exact error is:
[Error] TypeError: 'undefined' is not a function (evaluating 'geoArray.forEachObject')
Edit, the error occurs always within the collision loop and as soon as 'obj' is called.
Upvotes: 0
Views: 3906
Reputation: 4906
The method you're using to iterate through the array is not correct. The forEachObject
is not a method of a plain JavaScript Array. It is a method defined on fabric.Collection
.
The error simply indicates that you trying to use an undefined type as a function; You can either iterate using the forEach
method or using a common for
loop.
Upvotes: 2