4

I am working on image cropper using fabric js version 1.7.22. As usually, every cropper display black transparent overlay over the image (where image look like dull), and also display one Rect. (crop Area where image look full with color).

we can create this functionality using fabric js with background image and fabric.Rect object.

My problem is that when I use GlobalCompositeOperation with destination-out property to fabric.Rect object. It will make hole through canvas.

In simple word :

when I add globalCompositeOperation to destination-out, it will make hole through canvas also.

Expected result of canvas: enter image description here

Current Result of canvas: enter image description here

I have made one codepen for demonstration : https://codepen.io/mayurkukadiya0/pen/zYYWOGL?editors=0110

I have found one codepen also for do same but they are add multiple canvas for display image in separate layer and rect and overlay in separate layer Is there any way to do this without add external any canvas or css image behind canvas ? Here is that reference : https://codepen.io/s0nnyv123/pen/eravaN

Mayur Kukadiya
  • 2,461
  • 1
  • 25
  • 58

1 Answers1

3

try using setOverlayImage

here'a demonstration, based on your codepen

var canvas = new fabric.Canvas('canvas', {preserveObjectStacking: 'true'});
canvas.setHeight(300);
canvas.setWidth(300);

canvas.setOverlayImage('https://images.pexels.com/videos/856973/free-video-856973.jpg?auto=compress&cs=tinysrgb&dpr=1&w=500', canvas.renderAll.bind(canvas), {
    top: 0,
    left: 0,
    width: 300,
    height:300,
    lockMovementX: true,
    lockMovementY: true,
    lockRotation: true,
    selectable: false,
   globalCompositeOperation: 'destination-atop',
});

var overlay = new fabric.Rect({
    left: 0,
    top: 0,
    width: 300,
    height: 300,
    fill: '#00000050',
    selectable: false,
    globalCompositeOperation: 'source-over'
});
canvas.add(overlay);

var rect = new fabric.Rect({
     left: 100,
     top: 100,
     width: 100,
     height: 100,
     fill: '#451245',
     globalCompositeOperation: 'destination-out'
});
canvas.add(rect);
canvas.renderAll();
Ethan
  • 31
  • 3