最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - fabricjs delete backgroundImage - Stack Overflow

programmeradmin11浏览0评论

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

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

Share Improve this question edited Jan 6, 2013 at 14:09 kangax 39.2k13 gold badges100 silver badges135 bronze badges asked Jan 5, 2013 at 11:36 droiddudedroiddude 1871 gold badge4 silver badges15 bronze badges 1
  • 8 Just set it to an empty string — canvas.setBackgroundImage('', canvas.renderAll.bind(canvas)) (2nd argument here is a callback, to re-render canvas after background image is removed) – kangax Commented Jan 6, 2013 at 14:11
Add a ment  | 

3 Answers 3

Reset to default 12

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.

Set the background image to null will remove it.

canvas.setBackgroundImage(null, canvas.renderAll.bind(canvas));

You can also write a function like this to clear both the background image and background color which is handy.

function clearCanvasBackground() {
  if (canvas) {
    canvas.setBackgroundImage(null);
    canvas.setBackgroundColor('');
    canvas.renderAll();
  }
}

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));
发布评论

评论列表(0)

  1. 暂无评论