Make a hole in the canvas or straight

I use fabric.js and I need a transparent rectangle to be on the canvas, but I need to use a background.
The problem is that I need the background to be transparent under the straight line.

I created a fiddle to illustrate my problem: http://jsfiddle.net/goooseman/5xLE4/2/ (I need the background to be transparent under the square).

I think it is impossible to make a hole in the background, but we can use another rectangle as the background. I created another fiddle to show it: http://jsfiddle.net/goooseman/cNJwL/1/ I use this code to create a rect background:

var backgroundRect = new fabric.Rect({
    left: 0,
    top: 0,
    fill: 'red',
    width: canvas.width,
    height: canvas.height
});

But how can I make a hole in the background rectangle under the top rectangle?

+4
source share
2 answers

Perhaps this could help (as found in this question ).

First you need to add the background canvas object to which you want to make a “hole”. Then you create a new object (cutter) and set the property globalCompositeOperation = 'destination-out', and then add it to the canvas.

Similar:

var h = new fabric.Rect({width: canvas.width, height: canvas.height, fill: 'rgba(0,0,0,0.5)'})
var z = new fabric.Circle({radius: 100, top:100, left: 100, globalCompositeOperation: 'destination-out'})
canvas.add(h).add(z)

Thus, you first add the global object, and then add the object as a “cutter”. I think that it will act as a cutter for everything, so if you have other objects "behind", they will also be cropped (did not test it).

Hope this helps!

+2
source

, , .

fabric.StaticCanvas('canvas');
canvas.setHeight(300);
canvas.setWidth(300);

var bgrect = new fabric.Rect({
    left:0,
    top:0,
    fill: 'red',
    width: 100,
    height: 300,
});
canvas.add(bgrect);
bgrect = new fabric.Rect({
    left:200,
    top:0,
    fill: 'red',
    width: 100,
    height: 300,
});
canvas.add(bgrect);
canvas.add(bgrect);
bgrect = new fabric.Rect({
    left:100,
    top:0,
    fill: 'red',
    width: 100,
    height: 100,
});
canvas.add(bgrect);
bgrect = new fabric.Rect({
    left:100,
    top:200,
    fill: 'red',
    width: 100,
    height: 100,
});
canvas.add(bgrect);

+1

All Articles