Search code examples
filterfabricjsblending

Blend Filter Not apply when call canvas function `loadFromJson`


When I perform blend filter on the image and convert canvas into JSON

Then It again I load canvas from that JSON, at that time my filter not applied.

I am using a fabric version 1.7.22

My filter code is like below :

canvas.getActiveObject().filters.push(new fabric.Image.filters.BlendColor({
                    color: '#ff0000',
                    mode: 'add',
                    alpha: 0.8
                }))
canvas.getActiveObject().applyFilters(canvas.renderAll.bind(canvas));

All other filter is working perfectly after the canvas load into JSON but only blend filter not work. Is there any property missing in my filter?

I have created one fiddle that represents the issue : http://jsfiddle.net/Mark_1998/1pc95xef/3/


Solution

  • It appears to be a bug caused by Blend.toObject() not saving its class type, so Blend filter ends up without type: 'Blend' when serialized. To deserialize the object correctly, Fabric parses its type property, and when it doesn't find one for the serialized filter, it just abandons it.

    Here's a patch you can use to fix this:

    fabric.Image.filters.Blend.prototype.toObject = function() {
      return fabric.util.object.extend(this.callSuper('toObject'), {
        color: this.color,
        image: this.image,
        mode: this.mode,
        alpha: this.alpha
      });
    }
    

    BaseFilter.prototype.toObject() does set the type property, so it makes sense to just extend Blend.prototype.toObject() from the object it returns.

    P.S: the latest fabric.js 2.4+ doesn't have this issue so it's one more reason to upgrade.