Chun-fan Ivan Liao
Chun-fan Ivan Liao

Reputation: 29

Fabric.js "reverse" and "layered" clipping/cropping

In the answer of this question, this fiddle does the "normal" cropping, i.e. the image outside the grayed-area rectangle will be cropped, and only the image inside the gray rectangle area will remain.

The key codes of "normal" cropping use the function "clipTo":

object.clipTo = function (ctx) {
    ctx.rect(
        -(eWidth / 2) + left, 
        -(eHeight / 2) + top, 
        parseInt(width * eScaleX), 
        parseInt(eScaleY * height)
    );
} 

What I want to achieve is doing a "reverse" cropping, i.e. the image inside the gray rectangle will be cropped, and only the image outside the gray rectangle area will remain.

This is the first part. The second part is to do "layered" cropping, i.e. the object with lower z-index value (object A) will be cropped by the object (object B) which has higher z-index value and overlaps the object A. The overlapped area of the object A will be cropped.

Is this doable? I spent much time but couldn't find the solution nor achieve this on my own.

Thanks in advance.

Upvotes: 3

Views: 989

Answers (1)

Yasir Rasool
Yasir Rasool

Reputation: 44

use an inverted clip path group as this example shows

      let clip_rect = new fabric.Rect({ left: 220, top: 150, width: 70, height: 50 });
      let g = new fabric.Group([clip_rect]);
      g.inverted = true
      g.absolutePositioned = true

      object.clipTo = g

Upvotes: 0

Related Questions