This question belongs to fabricJS and canvas. In following case check is there any object which property true (obj.background == true
). There can be several images on canvas. After the first object detection, I want to terminate the loop. How I do this? I ave used return false;
but does not work. Here is the function.
canvas.forEachObject(function(obj){
if(obj.isType('image') && obj.hasOwnProperty('background')){
if(!obj.background == true){
alert("true");
return false;
}
}
});
There is no way to stop or break a forEach() loop other than by throwing an exception.
To break a forEach() loop in TypeScript, throw and catch an error by wrapping the call to the forEach() method in a try/catch block. When the error is thrown, the forEach() method will stop iterating over the collection. Copied!
Open a PowerShell console session, type exit , and press the Enter key. The PowerShell console will immediately close. This keyword can also exit a script rather than the console session.
The ForEach-Object cmdlet performs an operation on each item in a collection of input objects. The input objects can be piped to the cmdlet or specified using the InputObject parameter. Starting in Windows PowerShell 3.0, there are two different ways to construct a ForEach-Object command. Script block.
Now i haven't used FabricJS (awaiting a spam of down-votes already) looking at the source there is a getObjects()
method. What this does is return an array of objects instead of a custom iterator like forEachObject()
.
So with that you could use all the normal array itteration methods like forEach()
, some()
, every()
etc which will allow you to do what you wish.
So my understanding is you want to check if the object is an image and if its background property is true, and abort the loop on the first occurrence? This should do it.
canvas
.getObjects()
.some(obj => {
if (obj.isType('image') && obj.hasOwnProperty('background') && obj.background === true) {
console.log('Aww shucks, you found me.');
return true;
}
});
Obviously this is pseudo code.
Essentially it will loop all objects and abort if your return true
. If any element does return true
the return value from some
will also be true
.
EDIT after Michał Dopieralski comment.
I overlooked the fact getObjects
can be passed a type and will filter the results for you. So using that things get even simpler.
canvas
.getObjects('image')
.some(obj => {
if (obj.background === true) {
console.log('Aww shucks, you found me.');
return true;
}
});
array some docs
fabricjs getObjects source
EDIT:
On a side note the hasOwnProperty
check shouldn't be required i don't think. So long as obj
is defined then accessing a property of it that doesn't exist will return undefined
. Which will fail the === true
check.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With