I’m trying to write a simple jQuery plugin to test whether a canvas is blank or not. However, I am having trouble returning a boolean.
(function ($) {
$.fn.extend({
isBlank : function() {
return this.each(function () {
var context = this.getContext('2d'),
imageData = context.getImageData(0, 0, this.offsetWidth, this.offsetHeight);
for (var i = 0; i < imageData.data.length; i += 4) {
if (imageData.data[i+3] !== 0) {
return false;
}
}
return true;
});
}
});
})(jQuery);
For some reason, this returns the canvas object, and not the boolean. When I take my code out of the each loop, however, it returns the boolean as expected.
How can I get this to work with the each loop?
It’s returning the canvas because that’s what’s being returned from the function
isBlank.return this.each(...)returns the jQuery objectisBlankwas called on.You need to set a variable before the
.each, set it to true or false when needed, and then return that instead.Note: Inside
.each,return falsefunctions likebreakandreturn truefunctions likecontinue.Example: