fabricjs: retain the correct indexes of an object's image filters after loadFromJSON
I managed to get this working by changing the way I applied and retrieved the filters (by type rather than index). I simply checked to see if the filter existed (by 'type' not index), then spliced the filter at the desired index.
Changed this function...
getFilter(index) {
var obj = canvas.getActiveObject();
return obj.filters[index];
}
to this...
getFilter(type) {
var obj = canvas.getActiveObject();
if (obj) {
filter = null;
obj.filters.forEach(function(f) {
if (f.type == type) {
filter = f;
}
});
return filter;
}
}
Changed this function...
applyFilter(index, filter) {
var object = canvas.getActiveObject();
object.filters[index] = filter;
object.applyFilters();
canvas.renderAll();
}
to this...
applyFilter(type, filterIndex, filter) {
var obj = canvas.getActiveObject();
var indexExists = false;
var filterFound = false;
if (obj) {
obj.filters.forEach(function(f, i) {
if (f.type == type) {
filterFound = true;
obj.filters[i] = filter;
}
if (filterIndex == i) {
indexExists = true;
}
});
if (!filterFound && indexExists) {
obj.filters.splice(filterIndex, 0, filter);
} else if (!filterFound && !indexExists) {
obj.filters[filterIndex] = filter;
}
}
obj.applyFilters();
canvas.renderAll();
}
Changed this function...
applyFilterValue(index, prop, value) {
var obj = canvas.getActiveObject();
if (obj.filters[index]) {
obj.filters[index][prop] = value;
obj.applyFilters();
canvas.renderAll();
}
}
to this...
applyFilterValue(type, filterIndex, prop, value) {
var obj = canvas.getActiveObject();
if (obj) {
obj.filters.forEach(function(f, i) {
if (f.type == type) {
obj.filters[i][prop] = value;
}
});
}
obj.applyFilters();
canvas.renderAll();
}