18

I've a canvas element and I create fabric object out of that. Now, I want to change the background color dynamically. The following doesn't work for me.

var x;

x = new fabric.Canvas("mycanvas", {
      backgroundColor : "#fff",
      selection: true
   });

x.backgroundColor = "#f00";

The background color is white and it doesn't get changed to red.

viji
  • 2,706
  • 5
  • 28
  • 34

1 Answers1

26

You need to render canvas after changing properties, because properties of object is just properties and not handled by event

http://jsfiddle.net/oceog/gDhht/

var canvas = new fabric.Canvas('c',{backgroundColor : "#0ff"});
console.log(canvas);
canvas.backgroundColor="red";
canvas.renderTop();
canvas.add(
  new fabric.Rect({ top: 100, left: 100, width: 50, height: 50, fill: '#f55' }),
  new fabric.Circle({ top: 140, left: 230, radius: 75, fill: 'green' }),
  new fabric.Triangle({ top: 300, left: 210, width: 100, height: 100, fill: 'blue' })
);

canvas.backgroundColor="green";
canvas.renderAll();
​

update: I tried with latest fabric, seems you not need renderAll() anymore.

zb'
  • 8,071
  • 4
  • 41
  • 68
  • So weird I was using canvas.setBackgroundColor and the color didn't take affect until I changed again. Then I tried this and it worked. bug? – Michael J. Calkins Oct 20 '13 at 06:06
  • 1
    [see this example (it's not mine)](http://jsfiddle.net/fabricjs/hXzvk/) they use renderAll to set color, – zb' Oct 20 '13 at 11:54
  • I see what they're doing, is there a preferred way of doing this or negatives to either or since they both work? – Michael J. Calkins Oct 20 '13 at 16:25
  • I not sure, [searching through the source](https://github.com/kangax/fabric.js/search?q=setBackgroundColor&ref=cmdform) shows no definition of that method, so I not sure which type of object it belongs to. – zb' Oct 20 '13 at 17:13
  • 1
    found definition [here](https://github.com/kangax/fabric.js/blob/b92e9575e07f7ba7443d605af74ae89a15c3f36d/src/static_canvas.class.js#L264). At the moment I answered this year ago, it has no setBackgroundColor – zb' Oct 20 '13 at 17:52
  • Thanks for finding that! I like the method in your answer way better. – Michael J. Calkins Oct 20 '13 at 17:57
  • the methods looks placed to be more universal such as place pattern image as "color" but I feel some *semantic corruption* with method named like this. – zb' Oct 20 '13 at 18:00