Fabricjs图像避免剪辑路径溢出

问题描述 投票:0回答:1

我正在实现一个系统,用 Fabricjs 裁剪和偏移图像。

将偏移量应用于图像对象,并使用另一个用于

clipPath
的矩形来实现裁剪。

为了偏移容器内的图像,我通过重写

cropOffset
方法实现了自定义属性
_renderFill
,如下所示:

fabric.Image.prototype['_renderFill'] = function (ctx) {
      let elementToDraw = this._element;
      if (!elementToDraw) {
        return;
      }

      let scaleX = this._filterScalingX;
      let scaleY = this._filterScalingY;
      let w = this.width;
      let h = this.height;
      let min = Math.min;
      let max = Math.max;
      // crop values cannot be lesser than 0.
      let cropX = max(this.cropX, 0);
      let cropY = max(this.cropY, 0);

      let elWidth = elementToDraw.naturalWidth || elementToDraw.width;
      let elHeight = elementToDraw.naturalHeight || elementToDraw.height;
      let sX = cropX * scaleX;
      let sY = cropY * scaleY;


      if (!this.cropOffset) {
        this.cropOffset = { x: -(w / 2), y: -(h / 2) };
      }

      // the width height cannot exceed element width/height, starting from the crop offset.
      let sW = min(w * scaleX, elWidth - sX);
      let sH = min(h * scaleY, elHeight - sY);
      let x = this.cropOffset.x;
      let y = this.cropOffset.y;
      let maxDestW = min(w, elWidth / scaleX - cropX);
      let maxDestH = min(h, elHeight / scaleY - cropY);

      elementToDraw && ctx.drawImage(elementToDraw,
        sX, sY, sW, sH,
        x, y, maxDestW, maxDestH
      );
    }

这让我执行以下操作。 移动图像来自:

enter image description here

致:

enter image description here

当我现在添加剪辑路径时,即使剪辑路径比图像大,裁剪也会按预期工作(红色是来自矩形的剪辑路径,绿色是图像): enter image description here

问题:如果我在有剪辑路径的情况下调整

cropOffset
并将图像移动到其对象边界之外,则会出现溢出,并且在放大或缩小时会闪烁。此处可见(在绿色边框之外渲染的图像): enter image description here

您对为什么会发生这种情况有任何想法或提示吗?

fabricjs
1个回答
0
投票

通过使用宽度和高度变量手动裁剪画布上下文来解决这个问题。还需要保存和恢复此操作的上下文。 我无法确切解释为什么这有效。

这是编辑后的代码:


      
      ctx.save();
      ctx.beginPath();
      ctx.rect(-w / 2, -h / 2, w, h);
      ctx.clip();

      elementToDraw && ctx.drawImage(elementToDraw, sX, sY, sW, sH, x, y, maxDestW, maxDestH);

      ctx.restore();
© www.soinside.com 2019 - 2024. All rights reserved.