没有FragmentSource的FabricJS图像过滤器?

时间:2018-07-10 04:42:21

标签: fabricjs

我有一个与WebGL不兼容的过滤器。有没有办法跳过编写fragmentSource的方法?我尝试覆盖filter子类上的fabric.Image.filters.BaseFilter applyTo以仅调用this.applyTo2d(options);,但没有得到任何图像数据。

applyTo: function(options) {
    if (options.webgl) {
      if (options.passes > 1 && this.isNeutralState(options)) {
        // avoid doing something that we do not need
        return;
      }
      this._setupFrameBuffer(options);
      this.applyToWebGL(options);
      this._swapTextures(options);
    }
    else if (!this.isNeutralState()) {
      this.applyTo2d(options);
    }
  },

1 个答案:

答案 0 :(得分:0)

我能够用最少的代码在webgl_backend.class.js中以非优化的方式完成此任务。

首先,对于非webgl过滤器,webgl后端需要后备:

this.fallback2dBackend = new fabric.Canvas2dFilterBackend();

然后,而不是运行所有过滤器:fabric.filterBackend.applyFilters(filters, this._originalElement, sourceWidth, sourceHeight, this._element, this.cacheKey);

执行以下操作:

  var newSource = fabric.util.createCanvasElement();
  newSource.width = sourceWidth;
  newSource.height = sourceHeight;
  var newSourceCtx = newSource.getContext('2d');
  newSourceCtx.drawImage(this._originalElement, 0, 0, sourceWidth, sourceHeight);

  filters.forEach(function(filter) {
    if (!filter) {
      return;
    }
    var backend = fabric.filterBackend;
    if (filter.fragmentSource === null) {
      backend = backend.fallback2dBackend;
    }

    backend.applyFilters(
      [filter], newSource, sourceWidth, sourceHeight, this._element);

    newSourceCtx.clearRect(0, 0, sourceWidth, sourceHeight);
    newSourceCtx.drawImage(this._element, 0, 0, sourceWidth, sourceHeight);

  }, this);

如果有人想将其重构为PR,我已经published a fork