Need to change the canvas background color while using fabric js

viji picture viji · Nov 1, 2012 · Viewed 34.2k times · Source

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.

Answer

zb' picture zb' · Nov 1, 2012

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();
​