Search code examples
javascriptangularjsfabricjs

FabricJS v. 2 beta – enable disable filter


I am trying to apply and remove a filter to my active object. My code will apply the filter but will not remove it:

 $scope.contrastFilter = function () {
        var obj = canvas.getActiveObject();
        if (!obj) return;

        if (obj.filters.Contrast) {
            obj.filters.Contrast = null;
        } else {
            obj.applyFilters([ new fabric.Image.filters.Contrast({ contrast: 15 })]);
        }
        canvas.renderAll();
   };

Solution

  • $scope.contrastFilter = function() {
        var obj = canvas.getActiveObject();
        if (!obj) return;
        if (obj.filters[0]) {
            delete obj.filters[0];
        } else {
            obj.filters[0] = new fabric.Image.filters.Contrast({
                contrast: 15
            });
        }
        obj.applyFilters();
        canvas.renderAll();
    };
    

    obj.filters is an array containing all filters, so while adding, push filter class to obj.filters and while removing , remove from that array.