简体   繁体   中英

how to make a hole through only overlay Rectangle using fabric js?

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: 在此处输入图像描述

Current Result of canvas: 在此处输入图像描述

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

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM