Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to change the canvas background color while using fabric js

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.

like image 994
viji Avatar asked Nov 01 '12 08:11

viji


1 Answers

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.

like image 194
zb' Avatar answered Sep 29 '22 11:09

zb'