图像上的 Fabric JS 设置填充不起作用

Fabric JS setting fill on an image is not working

我正在尝试使用 Fabric JS 在图像上设置填充。

为了演示我的问题,我参考了 fabricjs.com 上的 Kitchensink 演示 http://fabricjs.com/kitchensink

在下图中,我试图用绿色填充图像 RGB(69,242,81) 但是当我设置颜色时,没有任何反应。这个问题有什么解决方法吗?

我看过 floodFilling,但不幸的是,对于我的用例来说,性能太重了。

谢谢!

可能的解决方案

在玩这个演示时,我可能已经找到了一个可能的解决方案:`http://fabricjs.com/image-filters`

我 select 一个对象并选择模式 tint 并将 alpha 增加到最大值(见下图)

我得到了想要的结果(见下图) 使用这种方法有什么问题吗?

目前无法识别 属性 图片填充。这样做的一个原因是因为在不透明的图像后面绘制纯色会导致该颜色出现在图像的边缘。由于图像 class 继承了对象 class 的默认填充颜色 rgb(0,0,0)(黑色),这意味着每个图像都会有这样的轮廓,除非手动填充颜色改为 transparent.

但是,如果您确实希望图像尊重填充 属性,您可以通过简单覆盖图像 class 的 _renderFill 方法来实现。只要确保将任何不需要背景颜色的图像的填充设置为 transparent.

fabric.Image.prototype._renderFill = function(ctx) {
      var elementToDraw = this._element;
      if (!elementToDraw) {
        return;
      }
      var scaleX = this._filterScalingX, scaleY = this._filterScalingY,
          w = this.width, h = this.height, min = Math.min, max = Math.max,
          // crop values cannot be lesser than 0.
          cropX = max(this.cropX, 0), cropY = max(this.cropY, 0),
          elWidth = elementToDraw.naturalWidth || elementToDraw.width,
          elHeight = elementToDraw.naturalHeight || elementToDraw.height,
          sX = cropX * scaleX,
          sY = cropY * scaleY,
          // the width height cannot exceed element width/height, starting from the crop offset.
          sW = min(w * scaleX, elWidth - sX),
          sH = min(h * scaleY, elHeight - sY),
          x = -w / 2, y = -h / 2,
          maxDestW = min(w, elWidth / scaleX - cropX),
          maxDestH = min(h, elHeight / scaleY - cropY);
          
      //fill override start
      ctx.beginPath();
      ctx.rect(x, y, sW, sH);
      ctx.fill();
      //fill override end
          
      elementToDraw && ctx.drawImage(elementToDraw, sX, sY, sW, sH, x, y, maxDestW, maxDestH);
    };