Make a hole in canvas background or in a rect

canvas, fabricjs, html, javascript

Solution

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

You need to first, add the canvas background object to which you want to do the "hole". Then, you create a new object (the cutter), and set the property `globalCompositeOperation = 'destination-out'`, and then you add it to the canvas.

Just like this:

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)

This way, you add first the global object, and then you add the object as a "cutter". I think it will act as a cutter for everything, so if you have other objects "behind", they will be cut too (haven't tested it).

Hope this helps!!

Problem

I use fabric.js and I need a transparent rect to be on a canvas, but I need to use background. The problem is that I need background to be transparent under the rect. I've created a fiddle to illustrate my problem: http://jsfiddle.net/goooseman/5xLE4/2/ (I need background to be transparent under the square). I think that it is impossible to make a hole in a background, but we can use another rect as a background. I've created another fiddle to show it: http://jsfiddle.net/goooseman/cNJwL/1/ I use this code to make background rect: ``` 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 rect under the upper rect?

Original source

Related problems