FabricJS applyFilters to non-image objects

by codingdude

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/3.4.0/fabric.min.js"></script>
<canvas width="600" height="400" id="c"></canvas>

<img style="display:none" src="https://upload.wikimedia.org/wikipedia/commons/thumb/f/f5/Flag_of_the_United_States_%281912-1959%29.svg/1920px-Flag_of_the_United_States_%281912-1959%29.svg.png" id="my-image" crossorigin="anonymous">

JavaScript

fabric.Object.prototype.filters = [];


fabric.Object.prototype.applyFilters = function(filters) {

      filters = filters || this.filters || [];
      filters = filters.filter(function(filter) { return filter && !filter.isNeutralState(); });
      var img = new Image();
      img.src = this.canvas.toDataURL();
      this._originalElement = img;
      this._filteredEl = this.canvas;
      this.set('dirty', true);

      // needs to clear out or WEBGL will not resize correctly
      //this.removeTexture(this.cacheKey + '_filtered');
			//this._removeCacheCanvas();
      //this._updateCacheCanvas();
      
      if (filters.length === 0) {
        this._element = this._originalElement;
        this._filteredEl = null;
        this._filterScalingX = 1;
        this._filterScalingY = 1;
        return this;
      }

      var imgElement = this.canvas,
          sourceWidth = imgElement.naturalWidth || imgElement.width,
          sourceHeight = imgElement.naturalHeight || imgElement.height;

      if (this._element === this._originalElement) {
        // if the element is the same we need to create a new element
        var canvasEl = fabric.util.createCanvasElement();
        canvasEl.width = sourceWidth;
        canvasEl.height = sourceHeight;
        this._element = canvasEl;
        this._filteredEl = canvasEl;
      }
      else {
        // clear the existing element to get new filter data
        // also dereference the eventual resized _element
        this._element = this._filteredEl;
        this._filteredEl.getContext('2d').clearRect(0, 0, sourceWidth, sourceHeight);
        // we also need to resize again at next renderAll, so remove saved _lastScaleX/Y
        this._lastScaleX = 1;
        this._lastScaleY = 1;
      }
      if (!fabric.filterBackend) {
        fabric.filterBackend = fabric.initFilterBackend();
      }
      fabric.filterBackend.applyFilters(
        filters, this._originalElement, sourceWidth, sourceHeight, this._element,...