FabricJS clippath border color and move the overlay image behind clippath?

1.6k views Asked by At

I am trying to add the clippath area(rect object) over canvas using fabricJS. Currently i set Overlay Image to the canvas and in addition to that am adding clippath area to place objects. I successfully able to place the object inside the clippath, but the problem is whatever image i place it inside clippath has opacity(means object also has transparency), i know is because i set transparent image as overlay which is always top over other object.

My query is

  1. Can i set the clippath area alone to ignore overlay? Or atleast to set the preference like clippath is first priority and next overlay?
  2. Currently clippath has no border and i couldn't know where the clippath is? So is there a way to set the border over clippath area?

Here is my below code

HTML

<canvas id="ex8" width="300" height="400"></canvas>

JS

(function () {
  var canvas = new fabric.Canvas('ex8');
  canvas.controlsAboveOverlay = true;
  var clipPath = new fabric.Rect({ width: 100, height: 100, fill: 'red', top: 100, left: 100 });

  canvas.setOverlayImage(
    'https://i.ibb.co/88QkSMC/crew-front.png',
    canvas.renderAll.bind(canvas),
    {}
  );
  var group = new fabric.Group([
    new fabric.Rect({ width: 100, height: 100, fill: 'red', globalCompositeOperation: 'xor' }),

    new fabric.Rect({ width: 100, height: 100, fill: 'blue', top: 100 }),
    new fabric.Rect({ width: 100, height: 100, fill: 'green', left: 100, top: 100 }),
  ]);

  canvas.clipPath = clipPath;
  canvas.add(group);
})();

Appreciate your help !!!

FIDDLE

1

There are 1 answers

1
colourCoder On

Very interesting question.

The issue you encounter is linked to the order in which layers are being applied in Fabric.js.

As described in a related github post, the layers are applied as follows (from bottom up):

The order of various physical and functional "layers" of canvas

Hence, it's not that the clipPath is put on the T-shirt image (i.e. the Overlay image). It's the opposite, as the T-shirt layer is applied over the clipPath.

While it seems that the "transparency" comes from the clipPath resp. fabric group, it is actually coming from the Overlay image itself as the T-shirt in the image is transparent (the surrounding white background is not).

The opacity of the T-shirt image is also visible when hovering over it with a mouse (e.g. in file explorer as depicted below).

T-shirt image on white and light blue background.


As for the borders, you can add the following to your code:
group.set({
    borderColor: 'yellow',
    cornerColor: 'yellow',
    cornerSize: 6,
    transparentCorners: false
  });
group.setActiveObject(canvas);

Please note that the borders are only visible when the corresponding canvas item is activated. For more information, you can check this link on customization.