Aleksandra Chuprova
Aleksandra Chuprova

Reputation: 503

canvas background turns black after rerender fabric.js

I have the following situation: I draw the canvas with a background image and this works:

var canvasSection = new fabric.Canvas('buildSection', {
  selectionColor: 'rgba(94,213,94,0.2)',
  width: widthS,
  height: heightS,
  hoverCursor: 'pointer',
  backgroundColor: ({
    source: 'image/bordenconfigurator/background/background1.png',
    repeat: 'repeat'
  })

});

But then I need to clear canvas and to redraw it. at this point when I try to set background, instead of an image I see a black screen. In console I can see that the background image is set however. This is the code I'm trying:

$('#cForm').on('change', function() {

  if ($(this).val() == 'rectLandsc') {
    widthS = 600;
    heightS = 400;

  } else if ($(this).val() == 'rectPortr') {
    ....

  }
  canvasSection.clear();

  canvasSection.set({
    fill: 'rgba(0,0,0,0)',
    //  backgroundColor: ({source: 'image/bordenconfigurator/background/background1.png', repeat: 'repeat'})
  });
  //canvasSection.backgroundColor({source: 'image/bordenconfigurator/background/background.png', repeat:'repeat'});
  canvasSection.setBackgroundColor({
      source: 'image/bordenconfigurator/background/background.png'
    }),
    canvasSection.renderAll.bind(canvas);
  drawBaseForm();
  canvasSection.renderAll();

  console.log(canvasSection);
});

Is it a kind of a bug? Or am I doing something wrong? Could anyone help me out here?

Upvotes: 1

Views: 1753

Answers (1)

Durga
Durga

Reputation: 15604

canvas.setBackgroundColor({
  source: 'image/bordenconfigurator/background/background1.png',
  repeat: 'repeat'
}, canvas.renderAll.bind(canvas));

setBackgroundColor first parameter is color/pattern and second parameter is callback function.

DEMO

var canvas = new fabric.Canvas('c');
canvas.setBackgroundColor({
  source: 'http://fabricjs.com/assets/pug_small.jpg'
}, canvas.renderAll.bind(canvas));

function clearCanvas(){
 var background = canvas.backgroundColor;
 canvas.clear();
 setTimeout(function(){
  canvas.setBackgroundColor(background,canvas.renderAll.bind(canvas));
 },2000)
}
canvas{
 border: 2px dotted black;
}
<script src="https://rawgithub.com/kangax/fabric.js/master/dist/fabric.js"></script>
<button onclick='clearCanvas()'>clear</button>
<canvas id="c" width="500" height="500"></canvas>

Upvotes: 2

Related Questions