Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fabricjs delete backgroundImage

Is it possible to delete the backgroundImage in a fabric.Canvas after setting with:

canvas.setBackgroundImage('img_url',function() { 
    canvas.renderAll();

Or just go back to the standard background? To set the backgroundColor to white isn't working.

Thanks for helping! Greetings Max

like image 774
droiddude Avatar asked Jan 05 '13 11:01

droiddude


2 Answers

This is a snippet from renderAll function of fabric.Canvas;

...
if (this.backgroundColor) {
    canvasToDrawOn.fillStyle = this.backgroundColor;
    canvasToDrawOn.fillRect(0, 0, this.width, this.height);
}

if (typeof this.backgroundImage === 'object') {
    this._drawBackroundImage(canvasToDrawOn);
}
...

Clearly, the background color is, in fact, being set to white when you do canvas.backgroundColor = white;. But, since canvas.backgroundImage is still an Image object, it is drawn over whatever color you fill the background with.

So, when you don't want the backgroundImage to be drawn, you need to set it to 0. It doesn't work with null, since typeof this.backgroundImage === 'object' still evaluates to true in renderAll, prompting backgroundImage to be drawn. It works with canvas.backgroundImage = 0;, though.

Example.

like image 169
Rikonator Avatar answered Oct 04 '22 21:10

Rikonator


Hi my FabricJs version is 4.5.1

Both Solutions do not work for me. Because I am using FabricJs in angular with fabric types.

I have found a solution when I have check FabricJs source code.

We can simply

setBackgroundImage

with an empty

Fabric.Image Object.

This way we can achieve delete Background image Functionality.

Here is the code snippet which can be used for this solution.

const image = new fabric.Image('');
canvas.setBackgroundImage(image, canvas.renderAll.bind(canvas));
like image 34
Junaid Ahmed Avatar answered Oct 04 '22 23:10

Junaid Ahmed